经过长时间的搜索和大量的反复试验,我发现下面的代码在商店和类别页面上显示了可变产品。稍作修改后,即可正常工作。但它还会显示所有类别的变体,而不是仅显示当前类别的变体。
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;
}
所以我想知道是否有可能在商店中显示所有产品变体,并且在类别视图上仅显示属于该类别的变体。
答案 0 :(得分:0)
您能否删除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;
}
}