代码之家  ›  专栏  ›  技术社区  ›  Virik

隐藏Woocommerce中具有特定产品类别的产品

  •  2
  • Virik  · 技术社区  · 8 年前

    我们使用以下代码隐藏类别为“未分类”的产品:

    add_action('pre_get_posts', 'custom_pre_get_posts_query');
    function custom_pre_get_posts_query( $q ) {
        if (!$q->is_main_query()) return;
        if (!$q->is_post_type_archive()) return;
      $q->set('tax_query', array(
        array(
          'taxonomy' => 'product_cat',
          'field'    => 'slug',
          'terms'    => 'ukategorisert',
          'operator' => 'NOT IN',
        )
      ));
        remove_action('pre_get_posts', 'custom_pre_get_posts_query');
    }
    

    但由于某些原因,归档文件最终会在每个页面上显示不同数量的产品。看起来这些产品是隐藏的,但在分页时仍算作产品?

    我们无法找到此问题的原因或解决方案。请帮忙。

    1 回复  |  直到 8 年前
        1
  •  1
  •   LoicTheAztec    8 年前

    而不是使用 pre_get_posts 钩子函数,您应该使用一个相关的专用Woocommerce操作和过滤器钩子。

    请尝试以下操作:

    add_filter('woocommerce_product_query_tax_query', 'custom_product_query_tax_query', 10, 2 );
    function custom_product_query_tax_query( $tax_query, $query ) {
        if( is_admin() ) return $tax_query;
    
        // HERE Define your product category SLUGs to be excluded
        $terms = array( 'ukategorisert' ); // SLUGs only
    
        // The taxonomy for Product Categories
        $taxonomy = 'product_cat';
    
        $tax_query[] = array(
            'taxonomy' => $taxonomy,
            'field'    => 'slug', // Or 'name' or 'term_id'
            'terms'    => $terms,
            'operator' => 'NOT IN', // Excluded
        );
    
        return $tax_query;
    }
    

    此代码继续运行。活动子主题(或主题)的php文件。它应该会起作用。