使用 pre_get_post 自定义 Wordpress 查询


customizing Wordpress queries using pre_get_post

我从其他帖子示例中构建了以下片段,这些片段说以任何其他方式进行查询修改都会受到极大的鄙视,但它不起作用。我得到的结果包括显然不应该发生的未发布的帖子和页面:

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(); 

get 变量如下所示:?s=mysearchterm&submit=+GO%21+

在我的博客模板上,我正在使用 verbotten query_posts() 函数来实现相同的效果,并且效果很好。

我不知道出了什么问题。有什么想法吗?

由于此代码存在于您的模板中,因此它不会及时触发以捕获pre_get_posts钩子。 选择/运行模板时,wp_query已完成设置,pre_get_posts结束。

您需要将此功能移动到functions.php文件中,并尝试使用其他一些方法来确定是否要更改查询。 有很多信息可供您使用 - 包括它是存档,单个页面,单个帖子,帖子ID等 - 希望通过这些信息,您可以确定是否要修改查询。