繁体   English   中英

从WordPress WooCommerce商店中排除类别

[英]Exclude categories from WordPress WooCommerce shop

我一直在尝试寻找一种方法,以从按显示子类别显示的WooCommerce商店首页中排除名为“特色”的特定类别。

我发现此脚本放置在我的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' );

}

为了解决上述问题-我想从商店页面上的任何位置排除特定类别。

我将此内容添加到了<?php标签开头下方的顶部content-product_cat.php页面中,并修改了类别名称以反映我需要隐藏的类别。 您可以用逗号分隔来广告多个类别。

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

就我而言,我想禁用商店产品列表中的所有类别,包括将来的类别,因此我转到了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(); ?>

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

我只是评论了这两行,发现行得通。 我不确定它随后对这些评论的后果。

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

您必须将以下代码添加到functions.php到您的子主题中

首先,您必须找到类别slug,然后在这里找到方法:

请记住,类别SLUG是类别的简短标题。

第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.
}}

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

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

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

记住要写下类别标签名称而不是myCat1 ... myCat4

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

祝好运 :)

暂无
暂无

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

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