dongsheng8664 2014-12-12 15:33
浏览 43
已采纳

循环内的Wordpress循环

I have a normal loop that outputs posts based on the given $args. After three posts I want to insert a post that is from a Featured category. I've tried starting a new WP_Query, simple query_posts in different combinations. Nothing seems to work. Any ideas why ?

$args = array(
    'post_type' => 'post', 
    'posts_per_page' => $count,
    'paged' => $paged,
    'page' => $paged,
    'cat' => $cat,
    'ignore_sticky_posts' => 1
);

// create a new instance of WP_Query
$my_query = new WP_Query($args);

<ul>
<?php 
$i = 0;
if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); 

 if($i == 3): ?>
    <li> //insert here one post from featured category
    </li>
<?php endif; ?>

<li>
// the normal query stuff is here
</li>
<?php $i++ //post counter
endwhile; //end loop while
endif; //end loop 
?>
</ul>
  • 写回答

1条回答 默认 最新

  • dousi8931 2014-12-15 12:26
    关注

    I did it this way. Before the main query I did a special query for the featured post.

    $args2 = array(
            'post_type' => 'post', 
            'posts_per_page' => 1,
            'category_name' => 'TheCategoryName-Slug',
            'ignore_sticky_posts' => 1
    );
    
    $my_query2 = new WP_Query($args2);
    $post_ids = array(); //create an array to store the ids of the posts
    if ($my_query2->have_posts()) : while ($my_query2->have_posts()) : $my_query2->the_post();
      $post_ids[] = get_the_ID();
     endwhile;
     wp_reset_postdata();
    endif;
    

    After you have all the ids you can use them to get the data you need. Basically, all the data from the wp_posts table (http://codex.wordpress.org/Database_Description#Table:_wp_posts). The post author is returned as an id that can be used to get the name using get_userdata() function.

    echo get_post_field('post_title', $post_ids[0]);
    echo get_post_field('post_author', $post_ids[0]);
    echo get_post_field('post_date', $post_ids[0]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)