【问题标题】:Custom product price suffix for selected product categories in WooCommerceWooCommerce 中所选产品类别的自定义产品价格后缀
【发布时间】:2020-04-04 16:32:06
【问题描述】:

我想在 WooCommerce 中的价格标签后显示一段文字。我有一个适用于我的 functions.php 的代码,但它显示在所有产品类别中。

我想知道是否有人知道如何使此自定义文本仅显示选定类别;甚至更好的是,未选择的产品类别,因为显示文本的产品类别比不显示的产品类别多得多。

我的实际代码:

add_filter( 'woocommerce_get_price_html', 'custom_price_message' );
function custom_price_message( $price ) {
    $mt = ' per M/T';
    return $price . $mt;
}

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy price


    【解决方案1】:

    尝试使用has_term() 条件函数定义产品类别的以下代码:

    add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 20, 2 );
    function conditional_price_suffix( $price, $product ) {
        // HERE define your product categories (can be IDs, slugs or names)
        $product_categories = array('t-shirts','hoodies');
    
        if( has_term( $product_categories, 'product_cat', $product->get_id() ) )
            $price .= ' ' . __('per M/T');
    
        return $price;
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。


    要排除已定义的产品类别,您将替换:

    if( has_term( $product_categories, 'product_cat', $product->get_id() ) )
    

    只需:

    if( ! has_term( $product_categories, 'product_cat', $product->get_id() ) )
    

    【讨论】:

    • 谢谢。我现在实现了它,它就像一个魅力! :)
    • 我想知道这段代码是否可以做另外 2 个功能:1. 不要添加后缀 w/o price 和 2. 也可以作为后缀的变体价格
    猜你喜欢
    • 2019-04-25
    • 2021-05-19
    • 1970-01-01
    • 2021-07-22
    • 2017-11-13
    • 2021-02-04
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多