显示类别下的产品

时间:2020-01-28 21:45:38

标签: wordpress woocommerce

我有以下代码在商店页面中按类别显示产品:

add_action('woocommerce_before_shop_loop', 'seperate_collection', 10);
function seperate_collection(){
    // men's collections
    if ( is_shop() ){
        $cat_args = array(
            'taxonomy' => 'product_cat',
            'parent' => 42 // for-him category id.
        );
        $categories = get_categories( $cat_args );
        foreach ($categories as $category) { 
            echo '<h3>' . $category->cat_name . '</h3>';
            echo do_shortcode('[products category="' . $category->slug . '" columns="4" orderby="date" order="DESC"]'); 
        }

    }

}

它正是我想要的。

但是我的问题是产品在列出的类别之后再次出现。 我尝试使用以下代码隐藏产品以免再次显示:

add_action( 'pre_get_posts', 'remove_products_from_shop_page' );

function remove_products_from_shop_page( $q ) {
   if ( ! $q->is_main_query() ) return;
   if ( ! $q->is_post_type_archive() ) return;
   if ( ! is_admin() && is_shop() ) {
      $q->set( 'post__in', array(0) );
   }
   remove_action( 'pre_get_posts', 'remove_products_from_shop_page' );
}

但是最终会删除所有商品,包括类别下的产品。

谢谢。

0 个答案:

没有答案