I wish to show in my front page a number of posts determined by the following criteria: show all posts from current month (actually from the month corresponding to the most recent post) ; but if that number is less that (say) 8, then show the 8 most recent posts.

Assuming that I know that no month will have more than (say) 20 posts, I'd tought of setting posts_per_page = 20, grab normally the most recent 20 posts, and afterwards do the appropiate trimming (slice) in php. (To do it in SQL seems too convoluted)

BTW: at first I thought that add_filter( 'posts_results', ... ) would be appropiate, but it's difficult to discriminate there whether the query corresponds to the main loop, or to some other query (eg., the Most-recent-posts widget...). I then coded the logic in the theme, in the index.php template.

The problem is that WP-query does not seem to support -cleanly- a trim of the posts... I must manually reassign the posts and count attribute (I think that the rewind() method should recompute the count, but...)

Do you feel this is too dirty? Any other ideas?

1 Answer 1


I think it would be better to just do a second query if you don't have 8 posts for that month, for example:

//get current date
$date = getdate();

//setup args
$args = array(
    //basic stuff
    'posts_per_page' => -1,
    'post_stutus'    => 'publish',
    //time parameters
    'year'           => $date['year'],
    'month_num'      => $date['mon']

//create WP_Query
$my_query = new WP_Query;

//execute first WP_Query
$posts = $my_query->query( $args );

//check first WP_Query, update if necessary
if( count( $posts ) < 8 ) {
    //update args
    unset( $args['year'] );
    unset( $args['mon'] );
    $args['posts_per_page'] = 8;

    //do query
    $posts = $my_query->query( $args );

//do your loop and such

That's some rough code that I just banged out real fast, but you get the idea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.