Remove WooCommerce custom related product tab if there are no related products

1.1k views Asked by At

In WooCommerce I ma using "WPB WooCommerce Related Products Slider" and "Custom Related Products for WooCommerce" third party plugins.

With the code below I am adding a custom tab to display related products:

remove_action( 'woocommerce_after_single_product_summary', 'wpb_wrps_related_products',22 );
add_filter( 'woocommerce_product_tabs', 'wpb_wrps_adding_related_products_slider_to_product_tab' );
if( !function_exists('wpb_wrps_adding_related_products_slider_to_product_tab') ){
    function wpb_wrps_adding_related_products_slider_to_product_tab( $tabs ) {
        $tabs['wpb_wrps_related_products_slider'] = array(
            'title'       => __( 'Related Products','wpb-wrps' ),
            'priority'    => 30,
            'callback'    => 'wpb_wrps_related_products'
        );
        return $tabs;
    }
}

As some of my products don't have related products, how can I make this tab displayed just when there is related products?

1

There are 1 answers

5
LoicTheAztec On

Here is the way to get the related products count for the current product. With that information we can conditionally make your custom tab display or not based on that count:

if( !function_exists('wpb_wrps_adding_related_products_slider_to_product_tab') ){
    add_filter( 'woocommerce_product_tabs', 'wpb_wrps_adding_related_products_slider_to_product_tab' );
    function wpb_wrps_adding_related_products_slider_to_product_tab( $tabs ) {
        global $product;
        // Get the related products count
        $related_count = count( maybe_unserialize( get_option( '_transient_wc_related_'.$product->get_id() ) ) );
        // If no related products we exit
        if( empty( $related_count ) || $related_count == 0 ) return $tabs;

        $tabs['wpb_wrps_related_products_slider'] = array(
            'title'       => __( 'Related Products','wpb-wrps' ),
            'priority'    => 30,
            'callback'    => 'wpb_wrps_related_products'
        );
        return $tabs;
    }
    // Just for testing
    function wpb_wrps_related_products() {
        echo '<h3>HERE your custom related products loop (fake)</h3>';
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested on Woocommerce 3+ and works