Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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'; } ?>" />
            </div>
            <p class="employee_name"><?php echo $name; ?></p>
            <small class="employee_title"><?php echo $title; ?></small>
        </div>
    <?php endforeach;
share|improve this question
add comment

1 Answer 1

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(
     array(
      'key'     => 'employee_pic',
      'value'   => '',
      'compare' => 'NOT LIKE'
     ),
   )
 ));
share|improve this answer
    
Smart! Thanks a lot. –  user1635 Mar 3 '11 at 11:39
add comment

Your Answer

 
discard

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