Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Multiple random queries - prevent duplicate posts WordPress

  • SOLVED

I've setup a very simple custom ads manager on a client's website. On one of their sidebars, there is to be a block of ads, followed by some standard HTML/content, and then another block of ads. I need to display 3 random ads in each ad block, but not show duplicate ads, and I'm having trouble putting the IDs into an array so that they're not queried in the second query - by using post__not_in.

Here's the code (minus the array stuff):


<?php
$args=array('showposts' => '3','post_type' => 'ads','post_status' => 'publish', 'orderby' => 'rand', 'caller_get_posts'=> 1);
$wp_query = new WP_Query($args);
get_template_part( 'loop', 'index' );
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>

<div class="ad"><a target="_blank" href="<?php echo get_post_meta($post->ID, 'link', true); ?>"><?php the_post_thumbnail(); ?></a></div>

<?php endwhile; endif; ?>

<!-- other content here -->

<?php
// this query needs to not show duplicates of any of the ads from the first query
$args=array('showposts' => '3','post_type' => 'ads','post_status' => 'publish', 'orderby' => 'rand', 'caller_get_posts'=> 1);
$wp_query = new WP_Query($args);
get_template_part( 'loop', 'index' );
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>

<div class="ad"><a target="_blank" href="<?php echo get_post_meta($post->ID, 'link', true); ?>"><?php the_post_thumbnail(); ?></a></div>

<?php endwhile; endif; ?>


Thanks in advance

Answers (2)

2011-02-01

John Cotton answers:


Change your first loop to this



if ( have_posts() ) : while ( have_posts() ) : the_post();
$firstAds[] = $post->ID;
?>


The change your second to this:


$args=array('showposts' => '3','post_type' => 'ads','post_status' => 'publish', 'orderby' => 'rand', 'caller_get_posts'=> 1, 'post__not_in'=> $firstAds );

$posts = query_posts($args);

// etc

2011-02-01

S├ębastien | French WordpressDesigner answers:

caller_get_posts (bool) - ignore sticky posts or not. Deprecated as of Version 3.1 in favor of 'ignore_sticky_posts'.