【问题标题】:Hide product category from category list on shop page in Woocommerce从 Woocommerce 商店页面上的类别列表中隐藏产品类别
【发布时间】:2018-02-18 04:15:36
【问题描述】:

我想在 Woocommerce 商店页面的类别列表中隐藏某个产品类别。我找到并使用了以下 sn-p 来做到这一点:

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 中有一个调试选项设置为 true,因此当 sn-p 工作并且“书籍”类别从列表中隐藏时,我收到以下错误:

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

它指向这条线:

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

这行写对了吗?还是我错过了什么?

【问题讨论】:

    标签: php wordpress woocommerce widget custom-taxonomy


    【解决方案1】:

    更新:您最好使用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 文件中。

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

    【讨论】:

    • 感谢您的帮助 .. 它仅适用于小部件,但不适用于类别列表。基本上在我的商店页面上,我在商店标题下方有一个类别列表。虽然它不是一个小部件。我为这个工作的代码和不需要的类别从列表中消失了,但它触发了上面提到的通知错误..
    • 如果我编辑archive-product.php 模板会怎样?类别列表显示为$terms = get_terms('product_cat'); 我可以在此处排除类别吗?
    • @JoeBloggs 我已经更新了我的代码……试试看。这次应该不会出错了。
    • 谢谢,代码有效,但我仍然遇到这个顽固的Notice :Trying to get property of non-object in 指向这条线if ( 'books' == $term->slug && $term->taxonomy = 'product_cat' ) 可能是别的东西吗?与代码冲突?
    • @JoeBloggs 我没有收到那个错误......但我已经轻轻更新了代码,使用$term 上的 PHP 条件 is_object() 以确保这是一个对象(一个 WP_Term 对象实例)……所以试试吧……我希望它会奏效。
    猜你喜欢
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2017-01-19
    • 2018-03-03
    • 2017-12-15
    相关资源
    最近更新 更多