我正在尝试从类别中检索帖子。我有2级和3级类别层次结构。我正在使用pre-get posts过滤器中的税务查询来更改查询。
对于第一级和第三级类别,查询工作正常,但对于第二级类别,查询结果不显示。检查时,查询在where子句中添加了0=1,用于不产生结果的查询。
对于2级类别,查询对于父类别和子类别都可以正常工作。
我用Wordpress安装了woocommerce。
下面是添加的过滤器:
add_action(\'pre_get_posts\', \'alter_category_search_query\');
function alter_category_search_query($query) {
if ($query->is_main_query() && $query->is_search) {
$args = array(
array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'slug\',
\'terms\' => $_GET[\'cat\'],
\'include_children\' => false
)
);
$query->set(\'tax_query\', $args);
//we remove the actions hooked on the \'__after_loop\' (post navigation)
remove_all_actions(\'__after_loop\');
}
}
生成的SQL:
SELECT wp_posts.* FROM wp_posts LEFT JOIN wp_term_relationships ON
(wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON (
wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND (
wp_term_relationships.term_taxonomy_id IN (17)
AND
0 = 1
) AND (
( wp_postmeta.meta_key = \'_visibility\' AND wp_postmeta.meta_value IN
(\'visible\',\'search\') )
) AND wp_posts.post_type = \'product\' AND (wp_posts.post_status = \'publish\')
GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC, wp_posts.post_title
ASC