WP_Query 不返回用于搜索查询的 ID [英] WP_Query Not Returning The ID for use in Search Query

查看:25
本文介绍了WP_Query 不返回用于搜索查询的 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to retrieve a list of IDs to remove from the search query based off of a WP_Query. For whatever reason the WP_Query is not displaying an array of IDs even though I know that post id 373 has the correct conditions of the query.

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:

After some investigation I found that by default the post loop uses only the post type of "post". I had to define all the post types I wanted to search for in order for it to bring back the ID of the page/custom post type that matched the values:

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 的问题,它并不能使搜索功能正常工作com/questions/52947360/post-not-in-is-not-exclusive-ids-from-wordpress-search-query">post__not_in 不排除 Wordpress 搜索查询中的 ID

Please note, this only fixes the issues of getting the page ids, it does not make the search function work I have another issue located here where you may find the fixed query: post__not_in is not excluding IDs from Wordpress Search Query

这篇关于WP_Query 不返回用于搜索查询的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆