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'm trying to have five advertisement locations, each pulling posts from the same custom post type, but also loading randomly. The only problem I have with my code below is that it will sometimes duplicate the posts shown. Is there a way so that all 5 advertisements display a random advertisement post without duplicating?

Here's one of the banners:

<div class="advertisement">
<?php query_posts('post_type=advertisement_posts&offset=1&orderby=rand&showposts=1');?>

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php $advert_url = get_post_meta($post->ID, 'rba_advert_url'); ?>
<?php $thumbnail_id = get_the_post_thumbnail($post->ID);
preg_match ('/src="(.*)" class/',$thumbnail_id,$link);
if(!empty($thumbnail_id)) {
$image_path =  thumbGen($link[1],234,116,"crop=1&halign=center&valign=center&return=1");
$image_all = get_bloginfo('url').$image_path;
$my_image = array_values(getimagesize($image_all));
list($width, $height, $type, $attr) = $my_image;
    <?php if(has_post_thumbnail()) : ?>
    <a href="<?php echo $advert_url[0]; ?>" target="_blank">
    <img src="<?php echo $image_path; ?>" alt="<?php the_title(); ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>"/>
    <?php endif; ?>

<?php endwhile; ?>
<?php endif;?>
<?php wp_reset_query(); ?>  

Any ideas?

share|improve this question

Fetch all five posts in one query, store the result in a variable and take one each time you want to show an advertisement.

Now you cannot get duplicates, and more important: you save four queries.

share|improve this answer

Your Answer


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

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