[英]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.