php - 在 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;
}
所以我想知道是否可以在商店中显示所有产品变体,并且在类别视图上只显示属于该类别的变体。
解决方案
您可以删除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;
}
}
推荐阅读
- c# - Xamarin 应用程序部署 - 应用程序包 (apk) 中是否包含所有依赖项?
- ios - 通过单击子视图中的按钮更改 UIView 显示
- rabbitmq - Pentaho - 如何将作业作为流运行
- jq - slurp 选项的 jq 等效项是什么?
- mysql - 规范化 MySQL 数据库未更新
- javascript - 根据选定的嵌套复选框生成 JSON
- laravel - 将 /index.php 重定向到 / 不使用 htaccess
- javascript - 如何使用给定 jQuery 选择中的元素生成对象
- java - 当应用程序在奥利奥中被杀死时,广播接收器不工作为什么?
- javascript - 使用 jQuery 将值附加到输入字段