1
votes

Having an issue with wordpress, using WP_Query to pull in the last three posts made in the last five days onto a page.

Here's my filter and where I set up the new instance of 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 ); 
?>

Then I've got my loop:

<?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; ?>

This all works well — the three posts are pulled in, but so are some extra posts that fall outside of the query.

Is there another function going on with pages that I haven't overridden? All of this code resides in a page template file, I suspect that there's some magic code that gets executed with pages that I can't seem to find.

Also, I know I'm grabbing these correctly because I can alter the number of posts shown with 'posts_per_page' or any other attribute, but the earlier posts that slip through aren't affected.

Thanks for your help, I can provide more code if needed.

2

2 Answers

1
votes

You should keep the following code in your 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' );

And following code in the page template file

$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;

Also, to make this work on a specific page you should add a condition in filter_where function, i.e.

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
votes

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

I had the exact same issue and found the answer in the link above. The issue was i had made a post sticky, which meant it was always being returned in my search results.

Adding the following into my query stopped this behaviour.

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