1

How could wp-query be used to show posts month by month, and have it only show the past year? Or is it possible some wp_archive hack could handle this?

1

3 Answers 3

3

WordPress 3.7 introduced the date_query to display posts month by month:

$args = array(
    'date_query' => array(
        array(
            'month' => $month
        )
    )
);
$query = new WP_Query( $args );

Note : $month refers to month number (1-12)

1
  • Perfect Solution!!!!.. Thanks for saving my time. :)
    – Raghav
    Jun 17, 2020 at 6:28
2

Well it's not a hack it's a function. You can simply use wp_get_archives

http://codex.wordpress.org/Function_Reference/wp_get_archives

Alternatively you can use a wp_query with a time format for actual content, for instance,

//December
$query = new WP_Query( 'monthnum=12' );

http://codex.wordpress.org/Class_Reference/WP_Query#Time_Parameters

1

Try this, I should clarify that the code is based on a snippet that I saw.

    <?php

$blogtime = date('Y');
$prev_limit_year = $blogtime - 1;
$prev_month = '';
$prev_year = '';

$args = array(
         'posts_per_page' => 20,
         'ignore_sticky_posts' => 1
);

$postsbymonth = new WP_Query($args);

while($postsbymonth->have_posts()) {

    $postsbymonth->the_post();

    if(get_the_time('F') != $prev_month || get_the_time('Y') != $prev_year && get_the_time('Y') == $prev_limit_year) {

                   echo "<h2>".get_the_time('F, Y')."</h2>\n\n";

        }

    ?>

        <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>

                <?php // your other template tags ?>


    <?php

    $prev_month = get_the_time('F');
    $prev_year = get_the_time('Y');

}

        ?>
1
  • 1
    Can you get this to print out the months with zero posts as well?
    – davebowker
    Aug 5, 2012 at 3:16

Your Answer

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

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