在Woocommerce单一产品页面上排除特定的产品类别 [英] Exclude specific product categories on Woocommerce single product pages

查看:102
本文介绍了在Woocommerce单一产品页面上排除特定的产品类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图排除某些类别,使其不在WooCommerce产品页面上显示。

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

示例:如果在单个产品页面中有类别:Cat1,Cat 2,我希望只显示Cat1

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

我尝试在单一产品模板中编辑 meta.php
我创建了一个新函数:

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;

然后我收到WooCommerce的回声:

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

,但仍显示相同的类别瑞斯。奇怪的是,当我执行 var_dump($ categories)时,它显示正确的内容。

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

推荐答案

您应该尝试将此自定义函数挂在 get_the_terms 过滤器钩中,该钩子将排除要在单个产品页面上显示的特定产品类别:

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

代码会进入您活动子主题的function.php文件中(或活动主题)。

经过测试并有效。

这篇关于在Woocommerce单一产品页面上排除特定的产品类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆