questions

WordPress: Display posts one year ago using WP_Query or get_posts()

Rate this post

I am trying to show the last six posts that were published at or before today but one year ago. I have the following code:

<?php 
$current_month = date('j');
$last_year   = date('Y')-1; 
?>
<?php query_posts('month='.$current_month.'month='.$current_month.'&year='.$last_year.'&posts_per_page=6'); 
    if (have_posts()): while (have_posts()) : the_post(); ?><div class="post-item">
        <div class="post-thumb-image">
            <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'grid-thumb' ); ?></a>
        </div>
        <div class="post-title">
            <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
            <p class="post-date"><?php echo get_the_date(); ?></p>
        </div>
    </div><?php endwhile; endif; ?>

It returns the last six posts of the current month one year ago. So if it is now December 10th 2020, it will show the last six posts of December 2019.

However, I want to show the last six posts that were published at or before today one year ago, so that it will show the last six posts published at or before December 10th 2019.

Another problem is that the code above uses query_posts(). This is supposed to be very inefficient, so I would like to know if I can achieve what I want by using WP_Query or ideally get_posts() instead.

 

✔️Solution:

You should try to use WP_Query with those kinds of parameters:

$args = array(
    'date_query' => array(
        array(
            'column' => 'post_date_gmt',
            'before' => '1 year ago',
        ),
    ),
    'posts_per_page' => 6,
);
$query = new WP_Query( $args );

Source: https://developer.wordpress.org/reference/classes/wp_query/#date-parameters

Leave a Reply

Your email address will not be published.

Back to top button