WordPress:WP_Query引入了额外的帖子

时间:2013-05-23 21:16:05

标签: wordpress

使用wordpress时遇到问题,使用WP_Query将过去五天内发布的最后三篇帖子拉到页面上。

这是我的过滤器以及我在哪里设置wp_query的新实例:

<?php 

get_header(); 

function filter_where( $where = '' ) {
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-5 days')) . "'";
    return $where;
}

$args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => '3'
            );

add_filter( 'posts_where', 'filter_where' );

$query = new WP_Query( $args ); 
?>

然后我得到了我的循环:

<?php while($query->have_posts()): $query->the_post();?>

<br/>
    <i><?php echo get_the_date(); ?></i>
    <br/>
    <b><?php the_title(); ?></b>
    <br/>
    <?php the_excerpt(); ?>
    <br/>
<?php endwhile; ?>

这一切都运作良好 - 这三个帖子都被拉入,但是一些额外的帖子也不在查询之内。

是否还有其他功能在我没有覆盖的页面上进行?所有这些代码都驻留在页面模板文件中,我怀疑有一些魔法代码会被我无法找到的页面执行。

此外,我知道我正确抓住了这些内容,因为我可以更改使用'posts_per_page'或任何其他属性显示的帖子数量,但之前发布的帖子不受影响。

感谢您的帮助,如果需要,我可以提供更多代码。

2 个答案:

答案 0 :(得分:1)

您应该在functions.php

中保留以下代码
function filter_where( $where = '' ) {
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-5 days')) . "'";
    return $where;
}
add_filter( 'posts_where', 'filter_where' );

并在页面模板文件中跟随代码

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => '3'
);
$query = new WP_Query( $args );
while($query->have_posts()): $query->the_post();
    // ...
endwhile;

另外,要在特定页面上进行此操作,您应该在filter_where函数中添加一个条件,即

if( is_page('page_slug') ) // or something like this
{
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-5 days')) . "'";
}
return $where;

Read more about is_page

答案 1 :(得分:0)

https://wordpress.stackexchange.com/questions/85657/wp-query-pulling-an-extra-post-per-page

我遇到了完全相同的问题,并在上​​面的链接中找到了答案。问题是我发了一个粘贴的帖子,这意味着它总是在我的搜索结果中返回。

将以下内容添加到我的查询中会停止此行为。

'ignore_sticky_posts' => true
$post_query =  new WP_Query();
$query_args =  array( 'ignore_sticky_posts' => true, 'post__in' => array(123,124), 'posts_per_page'=> '-1', 'order'=> 'ASC' , 'orderby' => 'title');
$myposts    =  $post_query->query($query_args);
相关问题