dongzhangji4824 2018-01-29 09:35
浏览 105
已采纳

在Woocommerce单品页面上排除特定的产品类别

I'm trying to exclude some categories from being displayed on the WooCommerce product page.

Example: if in a single product page I have "Categories: Cat1, Cat"2", I want that only Cat1 will be displayed.

I tried editing the meta.php in the single-product template. I created a new function:

$categories = $product->get_category_ids();
$categoriesToRemove = array(53,76,77,78); // my ids to exclude
foreach ( $categoriesToRemove as $categoryKey => $category) {
    if (($key = array_search($category, $categories)) !== false) {
        unset($categories[$key]);
    }
}
$categoriesNeeded = $categories;

Then I have the echo from WooCommerce:

echo wc_get_product_category_list( $product->get_id(), ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', count($categories), 'woocommerce' ) . ' ', '</span>' );

But it still shows the same categories. The strange thing is that when I do a var_dump($categories) it shows the correct thing.

  • 写回答

3条回答 默认 最新

  • douquqiang1513 2018-01-29 11:07
    关注

    You should try this custom function hooked in get_the_terms filter hook, that will exclude specific product categories to be displayed on single product pages:

    add_filter( 'get_the_terms', 'custom_product_cat_terms', 20, 3 );
    function custom_product_cat_terms( $terms, $post_id, $taxonomy ){
        // HERE below define your excluded product categories Term IDs in this array
        $category_ids = array( 53,76,77,78 );
    
        if( ! is_product() ) // Only single product pages
            return $terms;
    
        if( $taxonomy != 'product_cat' ) // Only product categories custom taxonomy
            return $terms;
    
        foreach( $terms as $key => $term ){
            if( in_array( $term->term_id, $category_ids ) ){
                unset($terms[$key]); // If term is found we remove it
            }
        }
        return $terms;
    }
    

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

    Tested and works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探