在 Woocommerce 中,我试图根据类别隐藏存档页面和单个产品页面上的产品,但该条件似乎不起作用,无论我是否设置类别,都只是隐藏所有价格
add_filter( 'woocommerce_variable_sale_price_html', 'woocommerce_remove_prices', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'woocommerce_remove_prices', 10, 2 );
add_filter( 'woocommerce_get_price_html', 'woocommerce_remove_prices', 10, 2 );
function woocommerce_remove_prices( $price, $product ) {
if(is_product_category('sold')){
$price = '';
return $price;
}
}
最佳答案
要使您的代码正常工作,您应该需要对单个产品页面使用 has_term()
条件函数,并且您需要始终在 之外返回价格if
语句:
add_filter( 'woocommerce_variable_sale_price_html', 'woocommerce_remove_prices', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'woocommerce_remove_prices', 10, 2 );
add_filter( 'woocommerce_get_price_html', 'woocommerce_remove_prices', 10, 2 );
function woocommerce_remove_prices( $price, $product ) {
if( is_product_category('sold') || has_term( 'sold', 'product_cat', $product->get_id() ) )
$price = '';
return $price;
}
有效!但这不会删除选定的产品变体价格,并且您仍然可以在任何地方添加添加到购物车按钮。
代码进入您的事件子主题(或事件主题)的 function.php 文件中。
相反,您可以使用以下内容删除该特定产品类别上的所有价格、数量按钮和添加到购物车按钮:
// Specific product category archive pages
add_action( 'woocommerce_after_shop_loop_item_title', 'hide_loop_product_prices', 1 );
function hide_loop_product_prices(){
global $product;
if( is_product_category('sold') ):
// Hide prices
remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
// Hide add-to-cart button
remove_action('woocommerce_after_shop_loop_item','woocommerce_template_loop_add_to_cart', 30 );
endif;
}
// Single product pages
add_action( 'woocommerce_single_product_summary', 'hide_single_product_prices', 1 );
function hide_single_product_prices(){
global $product;
if( has_term( 'sold', 'product_cat', $product->get_id() ) ):
// Hide prices
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
// Hide add-to-cart button, quantity buttons (and attributes dorpdowns for variable products)
if( ! $product->is_type('variable') ){
remove_action('woocommerce_single_product_summary','woocommerce_template_single_add_to_cart', 30 );
} else {
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
}
endif;
}
代码进入您的事件子主题(或事件主题)的 function.php 文件中。
经过测试并且有效。
关于php - 根据 Woocommerce 中的产品类别隐藏价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673253/