1

在 WooCommerce 中,我使用“WPB WooCommerce 相关产品滑块”和“WooCommerce 的自定义相关产品”第三方插件。

使用下面的代码,我添加了一个自定义选项卡来显示相关产品:

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

由于我的某些产品没有相关产品,我怎样才能让这个标签在有相关产品时才显示?

4

1 回答 1

0

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

于 2017-09-14T21:12:10.480 回答