问题
I have a tab set to add a tab which contains specifications in WooCommerce. I'd like to wrap it into an if statement to only set the tab if the product is part of a certain category.
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs' );
function woo_custom_product_tabs( $tabs ) {
global $post;
if ($product->is_category("Mobile Phones")) {
$tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
}
}
What is the right code to check the category for WooCommerce in the if statements brackets?
回答1:
The conditional is_category()
will return true if you are on a category archive page.
As you need a conditional for single product pages, you will target single product pages with is_product()
conditional combined this way:
if ( is_product() && has_term( 'Mobile Phones', 'product_cat' ) ) {
$tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
}
Or you could try also, in case, this one too:
if( is_product() && has_category( 'Mobile Phones' ) ) {
$tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
}
@edit: You've missed return $tabs;
at the end of your function before last closing bracket }
.
References:
- Remove product content based on category
- How to check if a woocommerce product has any category assigned to it?
回答2:
Try below code. This code add woocommerce tab only when product has Mobile Phones category.
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs' );
function woo_custom_product_tabs( $tabs ) {
global $post;
if ( is_product() && has_term( 'Mobile Phones', 'product_cat' ))
{
$tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
}
return $tabs;
}
来源:https://stackoverflow.com/questions/38613769/how-can-i-set-tab-only-if-the-product-is-in-a-certain-category-woocommerce