• Resolved pahroblem

    (@pahroblem)


    Hey guys i have a loop on my sidebar to show 5 random posts. works great but sometimes it can output posts from over a year ago. how would i add a filter so that only posts from up to 2months old will come up?

    <?php
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
    $first_tag = $tags[0]->term_id;
    }
    ?>
    
    <?php
    $args = array(
    'post_type' => array( 'post', 'review'),
    'posts_per_page' => 5,
    'post__not_in' => array( $post->ID ),
    'tag__in' => array($first_tag)
    
    );
    $the_query = new WP_Query( $args );
    ?>
    
    <?php if ( $the_query->have_posts('paged') ) : ?>

    Thanks in advance!

Viewing 8 replies - 1 through 8 (of 8 total)
  • Hi Pahroblem,

    I think the section of the Codex that you might find helpful as a reference for this would be: https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

    You would most likely need to add extra parameters to your $args array.

    Thread Starter pahroblem

    (@pahroblem)

    having trouble getting it into my array, loop seems to ignore it.

    Hi try this,
    <?php
    $args = array(
    ‘post_type’ => array( ‘post’, ‘review’),
    ‘posts_per_page’ => 5,
    ‘post__not_in’ => array( $post->ID ),
    ‘orderby’ => ‘date’,
    ‘tag__in’ => array($first_tag)

    );
    $the_query = new WP_Query( $args );
    ?>

    Would that work for you?

    Actually, using the date parameters you could do something like this too;

    <?php
    $args = array(
    ‘post_type’ => array( ‘post’, ‘review’),
    ‘posts_per_page’ => 5,
    ‘post__not_in’ => array( $post->ID ),
    ‘orderby’ => ‘date’,
    ‘tag__in’ => array($first_tag),
    ‘date_query’ => array(
    ‘after’ => date(‘Y-m-d’, strtotime(‘-2 months’))
    );
    $the_query = new WP_Query( $args );
    ?>

    Thread Starter pahroblem

    (@pahroblem)

    wouldnt that just order them by date dude? Tryin to get it to pull 5 randomly in no order but within 1 month old.

    Moderator keesiemeijer

    (@keesiemeijer)

    Have you tried it?

    Try setting orderby to rand.

    <?php
    $args = array(
    	'post_type'      => array( 'post', 'review' ),
    	'posts_per_page' => 5,
    	'post__not_in'   => array( $post->ID ),
    	'orderby'        => 'rand',
    	'tag__in'        => array( $first_tag ),
    	'date_query'     => array(
    		array(
    			'after' => '-2 months'
    		),
    	),
    );
    
    $the_query = new WP_Query( $args );
    ?>

    Hi,

    You can change the “orderby” to anything really, however the “after” is what we are after, to display post no older then 2 month.

    Hope that helps

    Thank you

    Thread Starter pahroblem

    (@pahroblem)

    My mistake…

    Yep that works. thanks for your help guys!

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Loop posts only 2 months old.’ is closed to new replies.