1

I'd like to randomize a set of posts (custom post type), but ignore the first post all together.

Here's the code I thought would work:

$featured_content_query = new WP_Query( array(
  'post_type'       => 'feature',
  'offset'          => 1,
  'posts_per_page'  => 10,
  'order'           => 'ASC',
  'orderby'         => 'rand'
) );

Without the orderby the post I want skipped over is ignored, but as soon as I add the random order it adds it back into the mix.

Does anyone know what I'm doing wrong? I feel like I'm missing something really obvious here.

Thnx!

2 Answers 2

1

I believe there are different ways of achieving this. Simplest way I could imagine is as below:

$featured_content_query = new WP_Query( array(
  'post_type'       => 'feature',
  'offset'          => 1,
  'posts_per_page'  => 10,
  'order'           => 'ASC'
 ) );

shuffle( $featured_content_query );    //PHP function to randomise posts array

You can then continue to use $featured_content_query as usual!

1
  • This is an efficient, straight forward way to achieve the goal. You could come up with 100 ways to exclude the most recent post from the query, but each of those will require at least one extra WP_Query (and therefore a DB call). With the solution by @sri you have an easy way to include your objective in one query then randomize. Feb 2, 2017 at 16:48
0

I was looking for another answer and stumbled on this, thought i could help.

If you looking to exclude the most recent post(s) you may be able to use wp_get_recent_posts() to retrieve the ID(s), and then use 'post__not_in' => array(#,#) in your WP_Query to exclude those resent posts.

Tested this a little and found this to work for getting ONE post to be excluded. I think you could parse the results differently to get more than just on ID if you so desired.

$recent = wp_get_recent_posts(array('post_type'=>$type,'numberposts'=>'1'));
$recentID[] = $recent[0]['ID']; // this creates an array of one

$args = array(
     'post_type'        => $type
    ,'post_staus'       => 'publish'
    ,'post__not_in'     => $recentID // array()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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