WordPress: How to make random posts excluding current and from chosen date

I need to have 5 random posts on post page (http://7cuteoutfits.com/2015/07/08/suits-rachel-z-office-fashion/) excluding current post. Random posts should be on chosen dates (for example posts from last 2 months until yesterday )
I added a few lines of code to single.php of my wordpress and now have 5 random posts. So I need to modify the code so that it will meet my requirements (above). I think it’s 2 more lines, I’ll be very thankful if you help.

<ul>
<?php
 $currentID = get_the_ID();
 $args = array(  'posts_per_page' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args);
foreach ( $rand_posts as $post ) : 
  setup_postdata( $post ); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; 
wp_reset_postdata(); ?>
</ul>

Related posts

1 comment

  1. You can use WP_Query for that.

    global $post;
    $args = array(
    'post__not_in' => array($post->ID)
    'orderby'   => 'rand'
    'date_query' => array(
        array(
            'after'     => 'January 1st, 2015',
            'before'    => array(
                'year'  => 2015,
                'month' => 07,
                'day'   => 9,
            ),
            'inclusive' => true,
        ),
    ),
    'posts_per_page' => 5,
    );
    $query = new WP_Query( $args );
    

    This query orders randomly posts between today (inclusive) and Jan. 1st 2015
    I haven’t tested the snippet here, so please let me know if it does not work for you.

    More info on WP_query and its usage (also for date parameters) here

    Once you query with WP_Query, you have to

    wp_reset_postdata();
    

    just as you are already doing.

    EDIT:

    To show the post content, you can call

    the_content()
    

    to print it directly, or

    get_the_content()
    

    to get it as a return value. Then you can handle the printing later with the HTML markup you desire.

Comments are closed.