近期文章功能

Avatar of Chris Coyier
Chris Coyier

方法 #1

当您需要显示内容、摘录、自定义字段或任何与文章相关的超出其链接和标题的内容时,此函数很有用。如果您只需要链接标题列表,请参见下一种方法。将以下函数放到 functions.php 中。

function recent_posts($no_posts = 10, $excerpts = true) {

   global $wpdb;

   $request = "SELECT ID, post_title, post_excerpt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='post' ORDER BY post_date DESC LIMIT $no_posts";

   $posts = $wpdb->get_results($request);

   if($posts) {

               foreach ($posts as $posts) {
                       $post_title = stripslashes($posts->post_title);
                       $permalink = get_permalink($posts->ID);

                       $output .= '<li><h2><a href="' . $permalink . '" rel="bookmark" title="Permanent Link: ' . htmlspecialchars($post_title, ENT_COMPAT) . '">' . htmlspecialchars($post_title) . '</a></h2>';

                       if($excerpts) {
                               $output.= '<br />' . stripslashes($posts->post_excerpt);
                       }

                       $output .= '</li>';
               }

       } else {
               $output .= '<li>No posts found</li>';
       }

   echo $output;
}

用法

创建好函数后。将以下内容放到侧边栏或您想要显示近期文章的任何位置。

<?php recent_posts(); ?>

您可以提供两个参数,第一个是文章数量,第二个是您是否想要显示摘录。因此 recent_posts(2, false) 将显示最近的两个文章标题。

方法 #2

<?php wp_get_archives( array(

    'type'            => 'postbypost',   // or daily, weekly, monthly, yearly
    'limit'           => 10,   // maximum number shown
    'format'          => 'html',   // or select (dropdown), link, or custom (then need to also pass before and after params for custom tags
    'show_post_count' => false,    // show number of posts per link
    'echo'            => 1     // display results or return array

) ); ?> 

方法 #3

方法 #1 的更简洁版本,也包含更标准化的查询字符串。

<?php
   $recentposts = get_posts('numberposts=12&category=4');
   foreach ($recentposts as $post) :
       setup_postdata($post); ?>
       <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>