douhu2370 2017-08-22 12:04
浏览 78
已采纳

WooCommerce - 如果产品没有类别,则隐藏相关产品

I am wondering if there is a way to hide the related product tab in the single product page only if the product has no categories set.

This is what I tried:

global $product; 

// Return the product categories
$categories = $product->get_categories( ', ', ' ' . _n( ' ', '  ', $cat_count, 'woocommerce' ) . ' ', ' ' );

if(empty($categories)){
        remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
    }

This was added to functions.php but it is not working. Anyone would have a better idea?

  • 写回答

1条回答 默认 最新

  • doudong8713 2017-08-22 12:23
    关注

    Yes it is possible, Try below code.

    function remove_related_product()
    {
        global $product; 
    
        $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
        $terms = wp_get_post_terms( $product_id, 'product_cat' );
    
        if(empty($terms))
        {
             remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
        }
    }
    add_action('woocommerce_after_single_product_summary', 'remove_related_product',10);
    

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

    This code is tested on WooCommerce 3+ and works

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程