Check if Product is in a Specific Category in Functions.php

I’ve added additional tabs to my product pages within my functions.php file and now need to wrap that in an if statement so the additional tabs only show on products within the category of “Models.” I’ve tried every way of doing it that I can find, and none of them work. They all get rid of the additional tabs on every page, even if it’s in the category specified.

I’ve tried everything mentioned on this question, and I’m assuming none of them have worked because that person is making edits to their single-product.php file, and I’m editing my functions.php file?

if ( is_product() && has_term( 'Models', 'product_cat' ) ) {
////Add Custom Tabs
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
// Adds a compare tab
$tabs['compare'] = array(
'title'     => __( 'Compare', 'woocommerce' ),
'id' => 'compare',
'priority'  => 50,
'callback'  => 'woo_compare_tab_content'
);
// Adds a warranty tab
$tabs['warranty'] = array(
'title'     => __( 'Warranty', 'woocommerce' ),
'id' => 'warranty',
'priority'  => 50,
'callback'  => 'woo_warranty_tab_content'
);
return $tabs;
}
function woo_warranty_tab_content() {
    $warranty = get_post_meta( get_the_ID(), 'wpcf-warranty', true );
    // Warranty Tab Content
        echo '<div class="fusion-title title sep-double">';
    echo '<h3 class="title-heading-left">Warranty</h3>';
        echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
        echo '</div>';
        echo "$warranty";
        }
function woo_compare_tab_content() {
    $compare = get_post_meta( get_the_ID(), 'wpcf-compare', true );
    // Comparison Tab Content
    echo '<div class="fusion-title title sep-double">';
    echo '<h3 class="title-heading-left">Compare</h3>';
        echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
        echo '</div>';
        echo "$compare";
}
}

2 Answers
2

Add your conditional to your function, instead of wrapping the hook and function. I’m pretty sure you’ll need to pass the post ID because this may not be running in the loop??? (check me on that). You can forgo the is_product() check inside the function as well since the hook is only triggered by woocommerce.

function woo_new_product_tab( $tabs ) {
global $post;
if ( has_term( 'Models', 'product_cat', $post->ID ) ) {

    // Adds a compare tab
    $tabs['compare'] = array(
    'title'     => __( 'Compare', 'woocommerce' ),
    'id' => 'compare',
    'priority'  => 50,
    'callback'  => 'woo_compare_tab_content'
    );
    // Adds a warranty tab
    $tabs['warranty'] = array(
    'title'     => __( 'Warranty', 'woocommerce' ),
    'id' => 'warranty',
    'priority'  => 50,
    'callback'  => 'woo_warranty_tab_content'
    );

}
return $tabs;
}

You’ll find some more explanation here: https://bloke.org/wordpress/conditional-woocommerce-product-tabs/

Leave a Comment