如何在不使用PHP中的循环的情况下,仅单独显示最近的第一篇和第二篇文章


How do I display only the first and second most recent post separately without using a loop in PHP?

我需要在不使用循环的情况下分别显示类别中的第一篇和第二篇最新帖子。以下是我尝试过的;item1div应该显示最新的,item2div应该显示第二个最新的。

  <div class = 'item item1'>
  <?php get_posts('numberposts=1&offset=1&category='); ?>
  <?php while (have_posts()) : the_post(); ?>
  <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><h3><?php the_title(); ?></h3></a>
  <?php endwhile;?>
    </div>
   <div class = 'item item2'>
  <?php get_posts('numberposts=2&offset=1&category='); ?>
  <?php while (have_posts()) : the_post(); ?>
  <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><h3><?php the_title(); ?></h3></a>
  <?php endwhile;?>
    </div>

有一个内置的函数,名为:wp_get_recent_posts()

具有以下参数:

<?php $args = array(
    'numberposts' => 10,
    'offset' => 0,
    'category' => 0,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'include' => ,
    'exclude' => ,
    'meta_key' => ,
    'meta_value' =>,
    'post_type' => 'post',
    'post_status' => 'draft, publish, future, pending, private',
    'suppress_filters' => true );
    $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
?>

示例:

<?php
    $args = array( 'numberposts' => '2' );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<div><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" ><h3>' .   $recent["post_title"].'</h3></a></div>';
    }
?>

来源:https://codex.wordpress.org/Function_Reference/wp_get_recent_posts

您可以使用get_posts来检索两个帖子,并将它们放在一个数组中,以便在任何您喜欢的地方使用。