I want to have a small header at the top of a page showing the featured images with a link to the related custom post type.

This is my code:

// Creates random image header within tax called(defaults to residential).
add_shortcode( 'rt-random-projects', 'rt_random_projects' );
function rt_random_projects($atts) {
  $a = shortcode_atts( array(
      'category' => 'residential',
  $query = new WP_Query(
      'post_type' => 'jf_projects',
      'posts_per_page' => '3',
      'orderby' => 'RAND',
      'tax_query' => array(
          'taxonomy' => 'project_types',
          'field' => 'slug',
          'terms' => $a['category'],
  $count = $query->post_count;
  $projects  ='<div>';
  while ( $query->have_posts() ) : $query->the_post();
        $projects .= '<div class="projectheaderimg"><a href="'.get_the_permalink().'">'.get_the_post_thumbnail('','small').'</a></div>';
  endwhile;  //end while posts
  $projects .='</div>';

  // Code
  return $projects;

This brings up my images and links to the posts, but it isn't random. No matter what I do it still shows only the same 3 posts. How can I make it pull 3 random posts?


2 Answers 2


Starting from WordPress version 4.5, you can use RAND(seed) with the orderby parameter.

However, when the value is simply RAND (i.e. the uppercase of rand), WP_Query ignores it and defaults to the default sorting (which is by the post date).

I've confirmed that by inspecting the $query->request:

  1. With 'orderby' => 'RAND', the ORDER BY clause is ORDER BY wp_posts.post_date DESC.

  2. With 'orderby' => 'rand', the ORDER BY clause is ORDER BY RAND().

So the solution is simple: Always use rand, unless you want to use a seed.

  • 1
    the things you learn!
    – rudtek
    Commented Mar 14, 2019 at 14:30

More than likely this is a problem with your host. A lot of the big name managed WP hosting companies disable orderby random by default. If they are good (WPEngine) you can reach out to their support and get that enabled. If they suck (GoDaddy) you might have less luck with that request.
If that's the case then you will need to write a function to get all the posts, assign each a random number and then order those by that number and pick the top n posts that way. Which is exactly as slow and bad as it sounds.

  • I'm on a bluehost vps, so I don't think it's disabled.
    – rudtek
    Commented Mar 13, 2019 at 20:58

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.