WP_Query 不返回用于搜索查询的 ID



我正在尝试检索要根据WP_Query从搜索查询中删除的 ID 列表。无论出于何种原因,即使我知道帖子 id 373 具有正确的查询条件,WP_Query也没有显示 ID 数组。

remove_action('pre_get_posts','exclude_pages_from_search');
$hidePages = new WP_Query( array (
'meta_key' => 'edit_screen_sitemap',
'meta_value' => 'hide',
'fields' => 'ids'
)); 
$hidePageIds = array($hidePages->posts);
$hidePageIdss = array($hidePages);
var_dump($hidePageIds); // array(1) { [0]=> array(0) { } }
var_dump($hidePageIdss); // displays query array
add_action('pre_get_posts','exclude_pages_from_search');
function exclude_pages_from_search($query) {
if ( !is_admin() ) {
if ( $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post__not_in', array($hidePages->posts));
}
}
}
}

经过一些调查,我发现默认情况下,post循环仅使用"post"的post类型。我必须定义所有要搜索的帖子类型,以便它带回与值匹配的页面/自定义帖子类型的 ID:

remove_action('pre_get_posts','exclude_pages_from_search');
$hidePages = new WP_Query( array (
'post_type' => array( 'post', 'page', 'offer', 'review', 'project' ),
'meta_key' => 'edit_screen_sitemap',
'meta_value' => 'hide',
'fields' => 'ids'
)); 
$hidePageIds = array($hidePages->posts);
$hidePageIdss = array($hidePages);
var_dump($hidePageIds); // array(1) { [0]=> array(0) { } }
var_dump($hidePageIdss); // displays query array
add_action('pre_get_posts','exclude_pages_from_search');
function exclude_pages_from_search($query) {
if ( !is_admin() ) {
if ( $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post__not_in', array($hidePages->posts));
}
}
}
}

请注意,这仅解决了获取页面ID的问题,它不会使搜索功能正常工作 我在这里有另一个问题,您可以在其中找到固定查询: post__not_in 不会从 Wordpress 搜索查询中排除 ID

最新更新