Scott Scott - 4 months ago 18
PHP Question

How can I set tab (only) if the product is in a certain category WooCommerce

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?

Answer

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: