1

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.

query_posts("post_type='random_posts'&order='DESC'&posts_per_page=10");
//shuffle(query_posts())
2

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(
        array(
            'column' => 'post_date_gmt',
            'after'  => '1 month ago'
        )
    )
);
// rest same as above   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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