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.
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.
You should keep the following code in your
functions.php
And following code in the page template file
Also, to make this work on a specific page you should add a condition in
filter_where
function, i.e.Read more about is_page.