在普通单个产品页面的自定义选项卡中显示“相关产品”

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

在 WooCommerce 中,我在下面有这段代码,用于将 "Related Products" 添加到自定义选项卡,并使其适用于使用短代码 [product_page id="99"][=23 的帖子=] 在页面和帖子上。

我在 functions.php 中使用的有效代码:

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();
}

现在的问题是我在正常的产品单页中出现空白标签。

如何让它在普通产品单页上也能正常工作?

谢谢

要使其也适用于单个产品页面,您需要添加一些条件并仅对单个产品页面重用 woocommerce_related_products()

所以你的代码现在是:

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();
}

这应该适用于页面上的产品简码和 post 一侧以及单个 woocommerce 正常产品页面。

代码进入您的活动子主题(或主题)的 function.php 文件。或者在任何插件 php 文件中。