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

dan*_*ski 2 php wordpress product custom-taxonomy woocommerce

我试图从 WooCommerce 产品页面上的显示中排除某些类别。

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

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

$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;
Run Code Online (Sandbox Code Playgroud)

然后我收到了来自 WooCommerce 的回声:

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

但它仍然显示相同的类别。奇怪的是,当我做一个var_dump($categories)它显示正确的事情。

Loi*_*tec 6

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

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;
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。

测试和工作。

  • @Frits 谢谢 :) … 因为这是在格式化和显示(在单个产品页面上)之前获取术语的根函数。 (2认同)