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条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?