【问题标题】:Apply wordpress snippet for specific category为特定类别应用 wordpress 片段
【发布时间】:2021-11-17 23:52:14
【问题描述】:

我需要应用一个 sn-p,其中显示 woocommerce 产品的最大可变价格,但仅在类别 ID 29 中。我没有设法做到这一点,所以我留下了没有类别的函数代码.它适用于最大可变价格。我希望有一个人可以帮助我!非常感谢。

 // define the woocommerce_variable_price_html callback 
function filter_woocommerce_variable_price_html( $wc_format_price_range, $instance ) { 
$index = strpos($wc_format_price_range, "– ");
$wc_format_price_range = substr($wc_format_price_range, $index+7);
//This will remove the first price by dividing the standard string with dash
//You may add a prefix like, $wc_format_price_range = "Max Price: $wc_format_price_range";
return $wc_format_price_range = "Max Price: $wc_format_price_range";; 
}; 
// add the filter 
add_filter( 'woocommerce_variable_price_html', 'filter_woocommerce_variable_price_html', 10, 2 
); 

【问题讨论】:

    标签: wordpress woocommerce hook e-commerce code-snippets


    【解决方案1】:

    在你的例子中,$instance 是 $product,所以我们可以使用它首先检查它是否属于类别 ID 29。

    我使用的是这个参考:WooCommerce Conditional Logic – Tags, Examples & PHP,你可以看到你可以使用 has_term() 函数来检查给定的产品是否属于一个集合类别。

    在您的情况下,您的代码将变为以下内容:

    // define the woocommerce_variable_price_html callback 
    function filter_woocommerce_variable_price_html( $wc_format_price_range, $instance ) { 
    
       // exit if product does not belong to cat 29
       if ( ! has_term( 29, 'product_cat', $instance->get_id() ) ) return $wc_format_price_range;
    
       $index = strpos($wc_format_price_range, "– ");
       $wc_format_price_range = substr($wc_format_price_range, $index+7);
       //This will remove the first price by dividing the standard string with dash
       //You may add a prefix like, $wc_format_price_range = "Max Price: $wc_format_price_range";
       return $wc_format_price_range = "Max Price: $wc_format_price_range";; 
    }; 
    
    // add the filter 
    add_filter( 'woocommerce_variable_price_html', 'filter_woocommerce_variable_price_html', 10, 2 
    ); 
    

    【讨论】:

    • ¡嗨,生意兴隆!谢谢你的帮助。我在这里收到一个错误: if ( !has_term( 29, 'product_cat', $instance->get_id() ) return $wc_format_price_range; ¿你能再检查一下吗?谢谢
    • 你是对的,缺少括号。现在应该可以工作了
    • ¡你是最棒的!非常感谢 muuuuuch :D
    • 感谢您解决类别问题!我想知道有没有办法让不在该类别的产品不显示可变产品的价格范围,而是显示最低价格。你有什么主意吗?你是最棒的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多