繁体   English   中英

在商店的WooCommerce存档页面上显示产品变化

[英]Show product variations on WooCommerce archive pages as shop

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

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

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

您能否删除posts_where的内容并尝试使用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;
 }
 }

暂无
暂无

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

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