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

使用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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数