WordPress Custom Query to show posts from last x years

I have found a way to show all posts from the current year with this code:

<?php
$today = getdate();
$lastyear = $today[ 'year' ];
$args = array( 
    //'nopaging' => true,
    'paged' => $paged,
    'category' => 1, 
    'posts_per_page' => 36,
    'year' => $lastyear,
);
query_posts( $args ); // The Query ?>

    <div id="grid">

    <?php while ( have_posts() ) : the_post(); // The Loop ?>
        <?php get_template_part( 'article', 'thumb' ); ?>
    <?php endwhile; ?>

    </div>

    <?php get_template_part( 'navigation' ); ?>

<?php wp_reset_query(); // Reset Query ?>

However, what I really want is to show posts from 2 years ago till today (it’s Jan 2014), meaning, posts from 2012 and 2013 and 2014. How do I do this?

Read More

Many thanks in advance.

Related posts

1 comment

  1. <?php
    $today = getdate();
    $args = array( 
        //'nopaging' => true,
        'paged' => $paged,
        'category' => 1, 
        'posts_per_page' => 36,
        'date_query' => array(
            array(
                'after' => $today[ 'month' ] . ' 1st, ' . ($today[ 'year' ] - 2)
            )
        )
    );
    $catgory_posts = new WP_Query( $args ); // The Query ?>
    
    <div id="grid">
    
    <?php if( $catgory_posts->have_posts() ) while ( $catgory_posts->have_posts() ) : $catgory_posts->the_post(); // The Loop ?>
        <?php get_template_part( 'article', 'thumb' ); ?>
    <?php endwhile; ?>
    
    </div>
    
    <?php get_template_part( 'navigation' ); ?>
    

    See date parameters at WordPress codex: https://developer.wordpress.org/reference/classes/wp_query/#date-parameters

Comments are closed.