首页 文章

从WordPress WooCommerce商店中排除类别

提问于
浏览
0

我一直试图找出一种方法来排除我的WooCommerce商店首页中显示的特定类别,该首页按show subatagories显示 .

我发现这个脚本放在我的WordPress主题的functions.php文件中,但似乎没有任何事情发生:

add_filter( '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' => array( 'featured' ),
        'operator' => 'NOT IN'
    )));

    remove_filter( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

4 回答

  • 0

    为了解决我的上述问题 - 我希望将特定类别排除在我的商店页面上的任何位置 .

    我将此添加到开头 <?php 标记正下方的页面content-product_cat.php,并修改了类别名称以反映我需要隐藏的类别 . 您可以使用逗号分隔多个类别 .

    if ( is_shop() && in_array( $category->slug, array( 'featured' ) ) ) {
      return;
    }
    
  • 0

    在我的情况下,我想禁用我商店的产品列表中的所有类别,包括未来的类别,所以我去了 archive-product.php 文件并评论了 woocommerce_product_subcategories() 函数 .

    <?php woocommerce_product_loop_start(); ?>
       <?php //woocommerce_product_subcategories(); //This line of code ?>
       <?php while ( have_posts() ) : the_post(); ?>
          <?php wc_get_template_part( 'content', 'product' ); ?>
       <?php endwhile; // end of the loop. ?>
    <?php woocommerce_product_loop_end(); ?>
    

    这样,每次我的客户创建新类别的产品时,我都不必回来 .

  • 1

    我简单评论了这两行,发现它们正在发挥作用 . 我不确定其后续评论这些内容的后果 .

    //if ( ! $q->is_main_query() ) return;
    //if ( ! $q->is_post_type_archive() ) return;
    
  • 0

    您必须将以下代码添加到 functions.php child theme

    首先你需要找到categories slug,在这里你可以这样做:

    记住类别SLUG是类别简称 .

    STEP 1.

    /*get cat slug or cat info*/
         add_action('woocommerce_archive_description', 
    'woocommerce_category_description', 2);
       function woocommerce_category_description() {
          if (is_product_category()) {
          global $wp_query;
        $cat = $wp_query->get_queried_object();
        echo "CAT IS:".print_r($cat,true); // the category needed.
    }}
    

    然后,您可以在商店页面上输入任何类别时查看类别信息 .

    因此,您必须添加此部分,以过滤您不希望在商店页面中显示的任何特定类别:

    STEP 2.

    /* Exclude Category from Shop*/
    add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 );
    function get_subcategory_terms( $terms, $taxonomies, $args ) {
      $new_terms = array();
    
      // if a product category and on the shop page
      if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() ) {
        foreach ( $terms as $key => $term ) {
          if ( ! in_array( $term->slug, array( 'myCat1', 'myCat2, 'myCat3','myCat4' ) ) ) {
            $new_terms[] = $term;
          }
    
        }
    
        $terms = $new_terms;
      }
    
      return $terms;
    }
    

    记得写下你的类别slug名称而不是myCat1 ... myCat4

    你必须像这样输入类别slug:if(!in_array($ term-> slug,array(' myCat1 ', ' myCat2 ', ' myCat3 ',' myCat4 ')

    祝好运 :)

相关问题