woocommerce_product_query不适用于产品类别页面



我有自定义过滤器,基于URL参数在我的woocommerce商店。在functions。php中,我有这样的内容:

add_action( 'woocommerce_product_query', 'filtry1' );
function filtry1( $q ){ 
$meta_query = $q->get( 'meta_query' );
$meta_query[] = array(
'key' => 'my_custom_key',
'value' => $_GET['my_custom_key'],
'compare' => '=='
);  
$q->set( 'meta_query', $meta_query ); }

这在主页上效果很好。我在最后一个查询中看到了额外的meta_query。

SELECT mysite_posts.ID FROM mysite_posts INNER JOIN mysite_postmeta ON ( mysite_posts.ID = mysite_postmeta.post_id ) WHERE 1=1 AND ( mysite_posts.ID NOT IN ( SELECT object_id FROM mysite_term_relationships WHERE term_taxonomy_id IN (7) ) ) AND ( ( mysite_postmeta.meta_key = 'my_custom_key' AND mysite_postmeta.meta_value = 'VALUE-FROM-$GET' ) ) AND mysite_posts.post_type = 'acf-field' AND ((mysite_posts.post_status = 'publish')) AND mysite_posts.post_name = 'field_61729c0b8644a' GROUP BY mysite_posts.ID ORDER BY mysite_posts.menu_order ASC, mysite_posts.post_title ASC LIMIT 0, 1 

但是如果我们在类别页面,那么这个查询不起作用。查询如下所示:

SELECT mysite_posts.* FROM mysite_posts WHERE ID IN (86) 

可以使用pre_get_posts动作钩子。它适用于商店和类别页面。

function filtry1($query) {
if( ! is_admin() && $query->is_main_query() && $query->query_vars['post_type'] == 'product') {
$query->set( 'meta_query', array (
array(
'key' => 'my_custom_key',
'value' => $_GET['my_custom_key'],
'compare' => '=='
)
));
}
}
add_action( 'pre_get_posts', 'filtry1' );

相关内容

  • 没有找到相关文章

最新更新