简体   繁体   English

在Woocommerce中隐藏商店页面上类别列表中的产品类别

[英]Hide product category from category list on shop page in Woocommerce

I wanted to hide a certain product category in the category list on the Woocommerce shop page. 我想在Woocommerce商店页面的类别列表中隐藏某个产品类别。 I found and used the following snippet to do so: 我发现并使用以下代码片段来做到这一点:

add_filter( 'get_terms', 'exclude_category', 10, 3 );
function exclude_category( $terms, $taxonomies, $args ) {
  $new_terms = array();
  // if a product category and on a page
  if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() ) 
  {
    foreach ( $terms as $key => $term ) {
      if ( ! in_array( $term->slug, array( 'books' ) ) ) {
        $new_terms[] = $term;
      }
    }
    $terms = $new_terms;
  }
  return $terms;
}

I have a debug option in my wp-config set to true and so while the snippet is working and the 'books' category is hidden from the list, I am getting the following error: 我在wp-config中将debug选项设置为true,因此,在代码段正常工作并且列表中隐藏“ books”类别时,出现以下错误:

Notice:: Trying to get property of non-object in

And it is pointing to this line: 它指向这一行:

if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() )

Is this line written correctly? 此行书写正确吗? or am I missing something? 还是我错过了什么?

Updated: You should better use unset() to remove the product category term from the array, this way: 更新:您最好使用unset()从数组中删除产品类别术语,方法是:

add_filter( 'get_terms', 'exclude_category', 10, 3 );
function exclude_category( $terms, $taxonomies, $args ) {
    $new_terms = array();
    if ( is_shop() ){
        foreach ( $terms as $key => $term ) {
            if( is_object ( $term ) ) {
                if ( 'books' == $term->slug && $term->taxonomy = 'product_cat' ) {
                    unset($terms[$key]);
                }
            }
        }
    }
    return $terms;
}

This code goes on function.php file of your active child theme (or theme). 这段代码将放在您活动的子主题(或主题)的function.php文件中。

Tested and works (does't throws an error). 经过测试并可以正常工作(不会引发错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM