WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to get post IDs from a custom post type randomly and the posts are posted within 30 days.
But I can't really find a solution. How can I do it?

This is my query.

share|improve this question
up vote 2 down vote accepted

Two notes beforehand:

  1. There is no (unless you created a CPT) post type random_posts.

  2. Don't use query_posts.

That being said, the following will do what you want:

Just the randomness

$args = array(
     'posts_per_page' => '10',
     'orderby' => 'rand' 
$random_posts = get_posts( $args );

foreach( $random_posts as $random_post ) {
    // do something
    echo $random_post->ID . '<br />\n'; // access Post ID, for instance

Reference: get_posts

Dates pre-3.7

So far, your 30 day post age restriction was not easily possible to achieve in a single query. You could easily fetch posts from the current month only like so:

$args = array(
     'posts_per_page' => '10',
     'orderby' => 'rand',
     'monthnum' => intval( date( 'n' ) )
// rest same as above

Which would work well for you at the end of a given month, but return bad results (i.e. nothing) on the first day of a month.

The other option would have been to query for much more posts than the required 10 and check for dates while looping through the results. Also feels hacky.
Fortunately, WP 3.7 is around the corner...

Dates starting from WP 3.7

WordPress 3.7 will introduce the date_query parameter. (Which is frickin' awesome.)
--> Usage

This will make your requirement simple as pie:

$args = array(
    'posts_per_page' => '10',
    'orderby' => 'rand',
    'date_query' => array(
            'column' => 'post_date_gmt',
            'after'  => '1 month ago'
// rest same as above   
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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