簡體   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