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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程