donglin9717
donglin9717
2012-12-22 10:22
浏览 53
已采纳

使用orderby = rand时拆分Wordpress循环

I would really appreciate a hand with the following:

  • I have a Wordpress page that displays posts using query_posts('cat=10&tag=parties&orderby=rand');

  • What I would like to do is split the list in half and insert text in the middle. Ideally the text would come from the WYSIWYG editor for the page in Wordpress. I guess I need two sets of "php query posts" with the second query excluding posts from the first?

Is anyone able to help?

Many thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqyy38265
    dqyy38265 2012-12-22 11:20
    已采纳

    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.

    点赞 评论

相关推荐