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 am using the get_posts tag to get 4 random posts from a custom post type. However, I only want to get a post IF it has the $pic_url set.

I´ve tried using...

if(!$pic_url) {continue;}

But that won´t work since i sometimes end up with displaying fewer than 4 posts (I allways want to display 4 posts).

$rand_posts = get_posts(array( 'numberposts' => 4, 'orderby' => 'rand', 'post_type' => 'ansatte', 'order' => 'ASC' ));
    foreach( $rand_posts as $post ) : 
        $pic_url = get_post_meta($post->ID, 'employee_pic', true); 
        $name = get_post_meta($post->ID, 'employee_name', true); 
        $title = get_post_meta($post->ID, 'employee_title', true); 
        <div class="alignleft employee_outer">
            <div class="employee_container">
            <img src="<?php if($pic_url) { echo $pic_url; } else { echo bloginfo('template_url') . '/images/default_profile_pic.png'; } ?>" />
            <p class="employee_name"><?php echo $name; ?></p>
            <small class="employee_title"><?php echo $title; ?></small>
    <?php endforeach;
share|improve this question
up vote 3 down vote accepted

only retrieve posts with that meta key:

$rand_posts = get_posts(array( 
  'numberposts' => 4, 
  'orderby' => 'rand', 
  'post_type' => 'ansatte', 
  'order' => 'ASC',
  'meta_key' => 'employee_pic',

or maybe use WP 3.1's meta_query:

$rand_posts = get_posts(array( 
  'numberposts' => 4, 
  'orderby' => 'rand', 
  'post_type' => 'ansatte', 
  'order' => 'ASC',
  'meta_query' => array(
      'key'     => 'employee_pic',
      'value'   => '',
      'compare' => 'NOT LIKE'
share|improve this answer
Smart! Thanks a lot. – user1635 Mar 3 '11 at 11:39

Your Answer


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