【问题标题】:WP_Query Not Returning The ID for use in Search QueryWP_Query 未返回用于搜索查询的 ID
【发布时间】:2018-10-22 15:26:30
【问题描述】:

我正在尝试根据 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));
            }
        }
    }
}

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    经过一番调查,我发现默认情况下,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 is not excluding IDs from Wordpress Search Query

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2014-03-13
      • 2019-10-11
      相关资源
      最近更新 更多