Get the last month with posts using a recursive function…

There is probably another way but I would like to understand why this code returns null...

I only have posts in october and here's the recursive function:

function last_post( $month,$year ) {
    $args  = array( 'monthnum' = $month, 'year' = $year );
    $query = new WP_Query( $args );
    var_dump( $month ); // int 11, int 10

    if( $query-have_posts() ){
       return $args;
    } else {
       last_post( $month-1, $year ); // here is the problem ?
    }
}

$args = last_post( 11, $year ); // null but ok with 10

Topic recursive wp-query php Wordpress

Category Web


Just need to add returnbefore the function.

function last_post( $month,$year ) {
    $args  = array( 'monthnum' => $month, 'year' => $year );
    $query = new WP_Query( $args );
    var_dump( $month ); // int 11, int 10

    if( $query->have_posts() ){
       return $args;
    } else {
       return last_post( $month-1, $year ); // here is the fix!
    }
}

$args = last_post( 11, $year ); // null but ok with 10

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.