繁体   English   中英

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

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

我想在Woocommerce商店页面的类别列表中隐藏某个产品类别。 我发现并使用以下代码片段来做到这一点:

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

我在wp-config中将debug选项设置为true,因此,在代码段正常工作并且列表中隐藏“ books”类别时,出现以下错误:

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

它指向这一行:

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

此行书写正确吗? 还是我错过了什么?

更新:您最好使用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;
}

这段代码将放在您活动的子主题(或主题)的function.php文件中。

经过测试并可以正常工作(不会引发错误)。

暂无
暂无

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

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