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.

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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路