dongyi9082 2018-10-22 15:26
浏览 74
已采纳

WP_Query不返回在搜索查询中使用的ID

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));
            }
        }
    }
}
  • 写回答

1条回答 默认 最新

  • duanjiong5023 2018-10-23 11:01
    关注

    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));
                }
            }
        }
    }
    

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog