首页 > 解决方案 > 在 WooCommerce 存档页面上将产品变体显示为商店

问题描述

经过长时间的搜索和大量的反复试验,我找到了下面的代码,可以在商店和类别页面上显示可变产品。稍作修改后,它工作正常。但它也会显示所有类别的变体,而不是只显示当前类别的变体。

add_action( 'pre_get_posts', 'custom_modify_query_get_posts_by_date' );

// Modify the current query

function custom_modify_query_get_posts_by_date( $query ) {
 if ( ! is_admin() && $query->is_main_query() ) {

    if ( is_post_type_archive( 'product' ) || is_product_category() || is_product_tag() ) {
       $query->set( 'order', 'ASC' );
           add_filter( 'posts_where', 'rc_filter_where' );
   }
     return $query;
 }
}

// Add products variation post type to the loop
function rc_filter_where( $where = '' ) {

   $type = 'product_variation';
   $where .= " OR post_type = '$type'";

   return $where;

}

我想我是否可以将 pre_get_posts 限制为应该工作的当前类别。尝试了很多东西,但我无法让它工作。

add_action( 'pre_get_posts', 'custom_modify_query_get_posts_by_date' );

// Modify the current query

function custom_modify_query_get_posts_by_date( $query ) {
 if ( ! is_admin() && $query->is_main_query() ) {

 if ( is_product_category() ) {
    $cate = get_queried_object();
    $cateID = $cate->term_id;

       $query->set( 'order', 'ASC' );
       $query->set('cat', $cateID);
           add_filter( 'posts_where', 'rc_filter_where' );
   } elseif ( is_post_type_archive( 'product' ) || is_product_tag() ) {
       $query->set( 'order', 'ASC' );
           add_filter( 'posts_where', 'rc_filter_where' );
   }
     return $query;
 }
}

// Add products variation post type to the loop
function rc_filter_where( $where = '' ) {

   $type = 'product_variation';
   $where .= " OR post_type = '$type'";

   return $where;
}

所以我想知道是否可以在商店中显示所有产品变体,并且在类别视图上只显示属于该类别的变体。

标签: phpwordpresswoocommerceproductvariations

解决方案


您可以删除posts_where's 并尝试使用tax_query 而不是$query->set('cat', $cateID); 吗?

add_action( 'pre_get_posts', 'custom_modify_query_get_posts_by_date' );

// Modify the current query

function custom_modify_query_get_posts_by_date( $query ) {
if ( ! is_admin() && $query->is_main_query()  && $query->is_tax('product_cat') ) {

if ( is_tax('product_cat')  ) {
$cate = get_queried_object();
$cateID = $cate->term_id;
$cateslug = $cate->slug;
$catetax = $cate->taxonomy;

//$query->set('cat', $cateID); 

$taxquery = array(
    'tax_query' => array(
    'taxonomy' => $catetax,
    'terms' => $cateslug,
    'field' => 'slug',
    'include_children' => true,
    'operator' => 'IN'
      )
    );

$query->set( 'tax_query', $taxquery );

$query->set( 'post_type', array('product', 'product_variation') );

   $query->set( 'order', 'ASC' );

} elseif ( is_post_type_archive( 'product' ) || is_product_tag() ) {
   $query->set( 'order', 'ASC' );

}
 return $query;
 }
 }

推荐阅读