我有下一个代码:
add_action(\'init\', \'bbloomer_hide_price_add_cart_not_logged_in\');
function bbloomer_hide_price_add_cart_not_logged_in() {
if (!is_user_logged_in()) {
remove_action(\'woocommerce_after_shop_loop_item\',
\'woocommerce_template_loop_add_to_cart\', 10);
remove_action(\'woocommerce_single_product_summary\',
\'woocommerce_template_single_add_to_cart\', 30);
remove_action(\'woocommerce_single_product_summary\', \'woocommerce_template_single_price\', 10);
remove_action(\'woocommerce_after_shop_loop_item_title\', \'woocommerce_template_loop_price\', 10);
add_action(\'woocommerce_single_product_summary\', \'bbloomer_print_login_to_see\', 31);
add_action(\'woocommerce_after_shop_loop_item\', \'bbloomer_print_login_to_see\', 11);
}
}
function bbloomer_print_login_to_see() {
echo \'<a href="\'.get_permalink(wc_get_page_id(\'myaccount\')).
\'">\'.__(\'Login to see prices\', \'theme_name\').
\'</a>\';
}
此代码用于woocommerce网站,并隐藏未登录用户的价格。它工作得很好。我想隐藏特定类别产品的价格。我想我必须在以下位置更改这部分代码:
if ( !is_user_logged_in() && is_category(\'my category\') ) { ... }
, 从理论上讲,这些改变应该是可行的,但我不明白为什么我没有得到预期的结果。谁知道为什么代码不起作用?
SO网友:Fabrizio Mele
这个is_category()
方法检查当前查询是否针对现有类别存档页。作为woocommerce,您应该使用is_product_category()
方法,并检查单个产品has_term($slug, \'product_cat\', $product_id)
方法
此代码将从存档页和单个产品页中删除价格:
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;
}
参考号:
Hide Price based on product category in Woocommerce