0

I want to change a WP_query parameter if there is not any posts matching the query. Specifically I want to change the monthnum value, if there is not any posts to show of the current month, I want to run the query again with the new monthnum value.

$query = new WP_Query (array('category_name'=> $cat,'year' => $ano, 'monthnum' => $monthnum, 'posts_per_page' => $posts_per_page, 'post__not_in' => array($id)));   

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

    //do something      

    endwhile;
else:

    $monthnum = $monthnum - 1;
    if($monthnum == 0){
        $monthnum = 12;
    }

    /*
      here I want to run the query again with the new $monthnum value
    */

endif;
wp_reset_query();

Do you know the solution? Help me, please! Thanks.

1
  • If I understand correctly this isn't just an alternate query if no posts are found, you want to keep reducing the month val by 1 until posts are found? Commented Feb 28, 2014 at 14:48

1 Answer 1

2

Perhaps you can change the parameters to an oldWP_Query-- I wouldn't know. But it's easy enough to create a new WP_Query for each query: Just save your parameter array in a variable, instead of passing it directly to WP_Query, and you can modify it as often as you want. Abbreviated code:

$params = array('category_name'=> $cat, 'year'=> $ano, 'monthnum'=> $monthnum, 
                'posts_per_page'=> $posts_per_page, 'post__not_in'=> array($id));

$query = new WP_Query($params);   
while (! $query->have_posts()) {
    $params['monthnum'] -= 1;
    if ($params['monthnum'] == 0) {
        $params['year'] -= 1;
        $params['monthnum'] = 12;
    }

    $query = new WP_Query($params);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.