Jaqueline Passos
Jaqueline Passos

Reputation: 1389

Modify wordpress query parameter inside loop

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.

Upvotes: 0

Views: 1678

Answers (1)

alexis
alexis

Reputation: 50200

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

Upvotes: 2

Related Questions