WP_Query pulling in extra posts

May 23, 2013 in answer

0 votes, 0.00 avg. rating (0% score)

ANSWER:

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.

Sheikh Heera from http://stackoverflow.com/questions/16725744