簡體   English   中英

在商店頁面上顯示產品子類別(非父類別)和產品

[英]Display product subcategories (not parent categories) and products on shop page

我有2個產品類別"current-probes""accessories" ,其中有一些子類別"flex-ct""tlar""test-lead"

我想在商店頁面中顯示我的子類別和產品。 我知道WooCommerce可以顯示父類別和產品,但不顯示子類別。

我還需要阻止顯示子類別的單個產品。

這是我嘗試過的代碼(位於我的functions.php文件中)

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ( ! is_admin() && is_shop() || is_product_category( array( 'current-probes', 'accessories' ))  ) {
    $q->set( 'tax_query', array(array(
        'taxonomy' => 'product_cat',
        'field' => 'slug',
        'terms' => array( 'flex-ct', 'tlar', 'test-lead' ), 
        'operator' => 'NOT IN'
    )));
}

remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}

這樣可以防止顯示子類別的各個產品,但是我需要實際的子類別才能在循環中顯示。

WooCommerce的設置僅顯示類別和產品,基本上我只希望它顯示子類別(而不是父類別)和產品。 我希望這是有道理的。

我一直試圖找出一個星期,我快要瘋了。 我覺得有一個簡單的解決方案我只是忽略了。

我做錯了什么? 我該如何實現?

謝謝

我幾乎找到了我想要的東西。 它實際上不使用pre_get_posts。 這是代碼:

add_filter( 'woocommerce_product_subcategories_args', 'filter_woocommerce_product_subcategories_args', 10, 1 ); 
function filter_woocommerce_product_subcategories_args( $array ) { 
if ( ! is_admin() && is_shop() ) {
    $category = get_term_by('name', 'Products', 'product_cat');
    $parent_id = ($category) ? $category->term_id : 10;
    $array['parent'] = $parent_id;

        return $array; 
}; 
}

這將輸出類別10的子類別。我唯一的問題是,我需要選擇多個父類別。 我對冒號使用這種語法不熟悉,因此不確定如何指定多個父類別。 這也阻止了子類別顯示在其父類別頁面上,我也不希望這種情況發生。 如果有人有任何反饋,將不勝感激。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM