wordpress调用最新文章五种方法包括排除置顶文章

代码2020-12-111,162 人已阅来源:网络

免插件调用最新文章 是我们在进行wordpress改造开发时常常面对的功能,搜集了网上几种常用的方法,当一个页面既有最新文章又有置顶文章时,我们要考虑在最新文章列表里排除掉置顶文章。

一、最简单的方法wp_get_archvies

WordPress最新文章的调用可以使用一行很简单的模板标签wp_get_archvies来实现

<?php get_archives('postbypost', 10); ?>  //(显示10篇最新更新文章)

或者

<?php wp_get_archives('type=postbypost&limit=20&format=custom'); ?>

  • type=postbypost:按最新文章排列
  • limit:限制文章数量最新20篇
  • format=custom:用来自定义这份文章列表的显示样式(fromat=custom也可以不要,默认以UL列表显示文章标题。)

二、query_posts()函数

通过WP的query_posts()函数也能调用最新文章列表, 虽然代码会比较多一点,但可以更好的控制Loop的显示,比如你可以设置是否显示摘要。具体的使用方法也可以查看官方的说明。

调用最新文章:(直接在想要呈现的位置放上以下代码即可)

<li>  
    <h2>最新文章</h2>  
    <?php query_posts('showposts=6&cat=-111'); ?>  
    <ul>  
        <?php while (have_posts()) : the_post(); ?>  
        <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>  
        <?php endwhile;?>  
     </ul>  
</li>

读取6篇文章,排除分类ID为111里面的文章

三、推荐WP_Query函数

<ul>
<?php $post_query = new WP_Query('showposts=10');
while ($post_query->have_posts()) : $post_query->the_post();
$do_not_duplicate = $post->ID; ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
</ul>

四、推荐get_results()函数

<ul>
<?php $result = $wpdb->get_results("SELECT ID,post_title FROM $wpdb->posts where post_status='publish' and post_type='post' ORDER BY ID DESC LIMIT 0 , 10");
foreach ($result as $post) {
setup_postdata($post);
$postid = $post->ID;
$title = $post->post_title;
?>
<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>"><?php echo $title ?></a> </li>
<?php } ?>
</ul>

五、最新文章中排除置顶文章

<h2>最新文章</h2>
<ul>
<?php
    $recentPosts =  new WP_Query(array('post__not_in' => get_option('sticky_posts')));
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
    <li> <a href="<?php the_permalink() ?>" rel="bookmark" class="title"><? echo  get_the_title(); ?></a><?php  the_time('m/d'); ?></li> 
<?php endwhile; wp_reset_query();?>
</ul>

六、小结

1、使用get_results()函数最快
2、推荐使用WP_Query()函数,灵活好控制,这也是官网推荐的函数