WooCommerce下拉框中为变体名称添加计算后的月份
WooCommerce变体名称自动关联月份的实现问题
我有一款全年售卖的WooCommerce服务类产品,仅允许用户购买当前及未来两个月的服务(例如:当前为9月,可购9、10、11月)。该产品初始包含4个变体,我编写了短代码用于自动计算并展示可购买的月份,但变体名称无法直接解析短代码,只能显示纯文本。
现有短代码(用于计算月份)
// shortcode function get_mes_anio( $attr ) { date_default_timezone_set( 'America/Argentina/Catamarca' ); setlocale( LC_TIME, 'es_ES', 'Spanish_Spain', 'Spanish' ); $args = shortcode_atts( array ( 'cant' => '0', ), $attr ); $mes_anio = ucwords( utf8_encode( strftime( "%B %Y", strtotime( $args['cant'] . " months" ) ) ) ); return $mes_anio; } add_shortcode( 'prox_meses', 'get_mes_anio' );
使用示例:[prox_meses cant="2"] 会输出 Noviembre 2022(即当前两个月后的月份)。
当前用于修改变体名称的代码
// get variations for a given product ID and shows the above shortcode function display_price_in_variation_options( $term, $term_obj ) { $product = wc_get_product(); $id = $product->get_id(); if ( empty( $term ) || empty( $id ) ) { return $term; } if ( $product->is_type( 'variable' ) && $product->get_id() === 30917 ) { $product_variations = $product->get_available_variations(); } else { return $term; } foreach ( $product_variations as $variation ) { if ( count( $variation['attributes'] ) > 1 ) { return $term; } $attribute = array_values( $variation['attributes'] )[0]; if ( $attribute === $term_obj->slug ) { $term .= ' (' . do_shortcode('[prox_meses cant="2"]') . ')'; } } return $term; } add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_options', 10, 2 );
当前问题与需求
当前代码仅能给指定产品(ID:30917)的所有变体添加固定的两个月后月份。我需要创建额外8个变体(总计12个),实现每4个变体对应一个月份(共3组,分别对应当前月、未来第一个月、未来第二个月)。
尝试过两种方案但均未实现:
- 方案1:让变体名称直接解析短代码(目前仅显示纯文本)
- 方案2:自动按变体分组,每4个切换计算月份
内容的提问来源于stack exchange,提问作者leandroprz
相关产品推荐
相关产品推荐

