WordPress多站点,显示所有网站,但只想显示最后2

时间:2016-07-06 10:33:44

标签: php wordpress

我需要显示网站网络的最后2个帖子。目前我正在检索所有网站的所有最新帖子,但只想显示其中的2个。

我有以下代码:

<?php
  $items = return_latest_posts();
  global $wpdb;
  $table_search = $wpdb->prefix . "searchinfo";
  $query = "SELECT * FROM `$table_search`";
  $wpdb->show_errors();
  $results = $wpdb->get_results($query);

  foreach ($results as $site){
    $item = return_latest_posts_single_site($site->username,$site->password,$site->database,$site->host,$site->db_prefix);
  ?>

<li>
  <h4><?php echo $site->sitename; ?></h4>

  <?php foreach($item as $res){  ?>
    <p class="date"><?php echo $res->post_date ?></p>
    <h4><a href="<?php echo $res->guid; ?>" target='_blank'><?php echo $res->post_title ?></a></h4>
  <?php } ?>

  <hr />

</li>

<?php } ?>

我如何才能只显示所有网站的最后两篇帖子?

提前致谢!

1 个答案:

答案 0 :(得分:1)

你可以考虑计算$ results foreach运行的次数,并将输出限制在前两圈:

<?php
  $items = return_latest_posts();
  global $wpdb;
  $table_search = $wpdb->prefix . "searchinfo";
  $query = "SELECT * FROM `$table_search`";
  $wpdb->show_errors();
  $results = $wpdb->get_results($query);

  $count = 0;
  foreach ($results as $site){

    $count++;
    $item = return_latest_posts_single_site($site->username,$site->password,$site->database,$site->host,$site->db_prefix);

    if ( $count < 3) {

  ?>

    <li>
      <h4><?php echo $site->sitename; ?></h4>

      <?php foreach($item as $res){  ?>
        <p class="date"><?php echo $res->post_date ?></p>
        <h4><a href="<?php echo $res->guid; ?>" target='_blank'><?php echo $res->post_title ?></a></h4>
      <?php } ?>

      <hr />

    </li>

<?php }} ?> 

More information on $wpdb;