在每个产品ID / WP的WooCommerce产品价格之后添加文本

时间:2020-03-15 13:45:49

标签: php wordpress woocommerce

在子主题的functions.php文件中有以下代码,效果很好。

function themeprefix_custom_price_message( $price ) { 

global $post;

$product_id = $post->ID;
$my_product_array = array( 270,373,378,506,1306,1311,1312,1444,1445,1447,1449,1930,1932,1933,1934,1935,1963,4146,4152,4153,4154 );//add in product IDs
if ( in_array( $product_id, $my_product_array )) {
    $textafter = ' Each/Min 12'; //add your text
    return $price . '<span class="price-description">' . $textafter . '</span>';
 } 
 else 
 { 
    return $price; 
 } 
}
add_filter( 'woocommerce_get_price_html', 'themeprefix_custom_price_message' );

但是,现在我需要添加另一组产品并在价格后启用不同的文本,即“每分钟8分钟”。我尝试了上述各项的各种更改,并且每次都关闭了该网站。如何调整以上内容以在价格后添加另一组(然后可能是另一组)带有不同文本的产品ID?预先感谢!

1 个答案:

答案 0 :(得分:0)

您可以保留现有阵列。通过从else中删除if来简化代码,然后开始声明并检查新产品数组,然后返回默认的纯价格文本...

function themeprefix_custom_price_message( $price ) { 

    global $post;

    $product_id = $post->ID;

    $my_product_array = array( 270,373,378,506,1306,1311,1312,1444,1445,1447,1449,1930,1932,1933,1934,1935,1963,4146,4152,4153,4154 );//add in product IDs

    if ( in_array( $product_id, $my_product_array )) {
        $textafter = ' Each/Min 12'; //add your text
        return $price . '<span class="price-description">' . $textafter . '</span>';
    } 

    $my_product_array2 = array( 9990,9991,9992 );

    if ( in_array( $product_id, $my_product_array2 )) {
        $textafter = ' Each/Min 8'; //add your text
        return $price . '<span class="price-description">' . $textafter . '</span>';
    }

    $my_product_array3 = array( 9993,9994,9995 );

    if ( in_array( $product_id, $my_product_array3 )) {
        $textafter = ' Each/Min 4'; //add your text
        return $price . '<span class="price-description">' . $textafter . '</span>';
    }

    return $price;  
}
add_filter( 'woocommerce_get_price_html', 'themeprefix_custom_price_message' );