将 "Related Products" 添加到 WooCommerce 中的自定义选项卡

Adding "Related Products" to a custom tab in WooCommerce

我无法将 "Related Products" 添加到选项卡并使其适用于使用短代码的帖子。这是放在我的 functions.php

中的短代码和完整代码

[product_page id="99"]

这是我在主题中使用的代码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 );
}
/*
* Place content in custom tab (related products in this sample)
*/
function woo_custom_product_tab_content() {
woocommerce_related_products();
}
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tab' );

这是我收到的错误:

Fatal error: Call to a member function get_upsells() on a non-object in public_html/wp-content/plugins/woocommerce/templates/single-product/up-sells.php on line 25

我认为您需要将全局 $product 对象与 WC_Product get_related() method 一起使用以避免此错误...

那么解决方案可能是:

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

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

由于这是未经测试的,我不保证任何事情......

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