我在首页的主查询上运行了一个简单的过滤器,它应该排除所有具有特定meta值的帖子(只包括没有meta\\u键集的帖子,或者meta\\u键与我们排除的内容不匹配的帖子)。但是,无论出于何种原因,它的表现都不如预期。
/**
* Hide posts from main query on front page.
*
* @since 1.0.0
*
* @param object $query WP Query object.
* @return object Modified WP Query object.
*/
function wpse_exclude_posts_from_main_query( $query ) {
// Make sure this only runs on the main query on the front page
if ( is_front_page() && $query->is_main_query() ) {
// Exclude posts that have been explicitly set to hidden
$query->set(\'meta_query\', array(
\'relation\' => \'OR\',
// Include posts where the meta key isn\'t set
array(
\'key\' => \'_wpse_custom_key\',
\'value\' => \'asdf\', // A value must exist due to https://core.trac.wordpress.org/ticket/23268
\'compare\' => \'NOT EXISTS\',
),
// Include posts where the meta key isn\'t explicitly true
array(
\'key\' => \'_wpse_custom_key\',
\'value\' => true,
\'compare\' => \'!=\',
),
) );
}
}
add_action( \'pre_get_posts\', \'wpse_exclude_posts_from_main_query\' );
这个元查询的每一半都可以独立工作。我可以看到所有没有关键字的帖子,或者所有有关键字但不正确的帖子。当结合使用时,如上所示,我只看到键确实存在且不为true的帖子(不存在部分被完全忽略)。
下面是正在生成的SQL(根据posts\\u请求过滤器):
SELECT SQL_CALC_FOUND_ROWS wp_posts.*
FROM wp_posts
LEFT JOIN wp_postmeta
ON (
wp_posts.ID = wp_postmeta.post_id
AND wp_postmeta.meta_key = \'_wpse_custom_key\'
)
INNER JOIN wp_postmeta AS mt1
ON (wp_posts.ID = mt1.post_id)
WHERE 1=1
AND wp_posts.post_type = \'post\'
AND wp_posts.post_status = \'publish\'
AND (
wp_postmeta.post_id IS NULL
OR (
mt1.meta_key = \'_wpse_custom_key\'
AND CAST(mt1.meta_value AS CHAR) != \'1\'
)
)
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
您可以看到,当涉及到元片段时,它确实在使用或在WHERE子句中,而不是像引用的bug所强调的那样使用和:
https://core.trac.wordpress.org/ticket/23268希望有人能提供一些急需的见解,因为我完全不知所措。