Edmund
Edmund

Reputation: 65

Split Wordpress loop whilst using orderby=rand

I would really appreciate a hand with the following:

Is anyone able to help?

Many thanks!

Upvotes: 1

Views: 239

Answers (1)

codewithfeeling
codewithfeeling

Reputation: 6576

Instead of using query_posts why don't you use a WP_Query? This will get you an array that you can query the size of, then you could then have a counter which increments and once it hits the halfway mark, you insert whatever you want and move on.

Set it up like this:

// first, run the main loop to get the text editor content
while(have_posts()) : the_post(); 
  // we just assign it to a variable at this point without printing it
  $content_to_insert = get_the_content(); 
endwhile;

// now we set up the query to get out all the party posts
$parties_query = array( 
  'cat' => 10, 
  'tag' => 'parties', 
  'orderby' => 'rand', 
  'posts_per_page' => -1 
);

// NB. you will not get ALL your results unless you use 'posts_per_page' or 'showposts' set to -1

// Now run a new WP_Query with that query
$parties = new WP_Query($parties_query);

// get the halfway point - needs to be a whole number of course!
$half = round( sizeof($parties)/2 );

// this is our counter, initially zero
$i = 0

while($parties->have_posts()) : $parties->the_post(); ?>

<?php if ($i == $half) : ?>

// we are halfway through - print the text!
<?php echo apply_filters('the_content', $content_to_insert); ?>

<?php else : ?>

// render your party stuff
// you can use tags reserved for use in the loop, eg.

<div class="party">
  <h2><?php the_title(); ?></h2>
</div>

<?php endif; ?>

<?php $i++; endwhile; ?>

Hope that works. It was a late old night of Christmas parties last night.

Upvotes: 1

Related Questions