If clauses in get_posts query

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…

Read More
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'; } ?>" />
            </div>
            <p class="employee_name"><?php echo $name; ?></p>
            <small class="employee_title"><?php echo $title; ?></small>
        </div>
    <?php endforeach;

Related posts

Leave a Reply

1 comment

  1. 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(
         array(
          'key'     => 'employee_pic',
          'value'   => '',
          'compare' => 'NOT LIKE'
         ),
       )
     ));