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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料