duanchandun1860 2016-02-27 11:05
浏览 157
已采纳

使用pre_get_post自定义Wordpress查询

I've built the following snippet from other post examples that say doing query modification any other way is punishable by great scorn, but it's not working. I'm getting results that include non-published posts and pages which clearly shouldn't happen:

function post_conditions($where)
{
    $where .= "AND post_content NOT LIKE '%::exclude tag::%'";
    return $where;
}
add_filter('posts_where','post_conditions');

    function mysearch($query)
    {
        $query->set('post_type','post');
        $query->set('post_status','publish');
        $query->set('posts_per_page',20);
        $query->set('paged',get_query_var('paged'));
    }

    add_action('pre_get_posts','mysearch');

    while( have_posts() ){
        the_post();

        echo get_the_excerpt();
        the_tags();

    } 
    if (get_query_var('paged'))
        my_paged_function();

    wp_reset_query(); 

The get variables look like so: ?s=mysearchterm&submit=+GO%21+

On my blog template, I'm using the verbotten query_posts() function to achieve the same effect and it works perfectly.

I don't know what's going wrong. Any ideas?

  • 写回答

1条回答 默认 最新

  • douchuoliu4422 2016-02-28 00:10
    关注

    Since this code lives in your template, it's not firing in time to catch the pre_get_posts hook. By the time the template is chosen / running, wp_query is done setting up, and pre_get_posts is over.

    You need to move this functionality into your functions.php files, and try and use some other means by which to determine if you want to change the query. There's lots of information available to you - including if it's an archive, a single page, a single post, the post id, and more - hopefully with that information, you can determine if you want to modify the query.

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了