SlyMurphy
SlyMurphy

Reputation: 155

Displaying “Related Products” in a custom tab for normal single product pages

In WooCommerce, I have this code below for adding "Related Products" to a custom tab and making it work on posts that are used with a short code [product_page id="99"] on pages and posts.

The code that I use in functions.php that is working:

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20);
/*
 * Register custom tab
 */
function woo_custom_product_tab( $tabs ) {

    $custom_tab = array( 
        'custom_tab' =>  array( 
            'title' => __('Custom Tab','woocommerce'), 
            'priority' => 9, 
            'callback' => 'woo_custom_product_tab_content' 
        )
    );
    return array_merge( $custom_tab, $tabs );
}
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tab' );

/*
* Place content in custom tab (related products in this sample)
*/
function woo_custom_product_tab_content() {
    global $product;
    $product->get_related();
}

Now the problem is that I get a blank tab in normal product single pages.

How can I make it work on normal product single pages too?

Thanks

Upvotes: 2

Views: 1006

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253949

To make it work also on single product pages you need to add some conditions and to reuse the woocommerce_related_products() just for single product pages.

So your code will be now:

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20);
/*
 * Register custom tab
 */
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tab', 20, 1 );
function woo_custom_product_tab( $tabs ) {

    $custom_tab = array( 
        'custom_tab' =>  array( 
            'title' => __('Custom Tab','woocommerce'), 
            'priority' => 9, 
            'callback' => 'woo_custom_product_tab_content' 
        )
    );
    return array_merge( $custom_tab, $tabs );
}

/*
* Place content in custom tab (related products in this sample)
*/
function woo_custom_product_tab_content() {
    global $product;
    if(!is_product())
        $product->get_related();
    else
        woocommerce_related_products();
}

This should work for your product shortcode on pages and post on one side and also on single woocommerce normal product pages.

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

Upvotes: 1

Related Questions