在 WordPress 中,调用最新文章是一个常见的需求。你可以使用 WP_Query
类或者内置的函数来实现这一功能。以下是几种常用的方式来调用最新的文章。
WP_Query
自定义查询最新文章<?php$args = array( 'post_type' => 'post', // 设置查询类型为文章 'posts_per_page' => 5, // 获取最新的5篇文章 'orderby' => 'date', // 按日期排序 'order' => 'DESC' // 按降序排列);$query = new WP_Query($args);// 开始循环输出文章if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?> <div class="latest-post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p><?php the_excerpt(); ?></p> </div> <?php endwhile;else : echo '没有找到最新的文章';endif; // 重置查询wp_reset_postdata(); ?>
get_posts()
函数get_posts()
是一个简化版的 WP_Query
,它也可以用来获取最新的文章。以下是使用 get_posts()
来获取最新文章的例子:
<?php$args = array( 'numberposts' => 5, // 获取最新的5篇文章 'orderby' => 'date', // 按日期排序 'order' => 'DESC' // 按降序排列);$latest_posts = get_posts($args);if (!empty($latest_posts)) : foreach ($latest_posts as $post) : setup_postdata($post); ?> <div class="latest-post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p><?php the_excerpt(); ?></p> </div> <?php endforeach; wp_reset_postdata();else : echo '没有找到最新的文章';endif; ?>
query_posts()
(不推荐)虽然 query_posts()
可以直接查询并显示最新的文章,但它会修改主查询,通常会影响整个页面的查询结果。因此,不推荐在模板中使用 query_posts()
,推荐使用 WP_Query
或 get_posts()
。
如果你希望在 WordPress 中使用小工具来显示最新文章,可以在后台操作:
转到 外观 > 小工具
。
找到 最新文章
小工具,拖动它到你的侧边栏或其他小工具区域。
设置显示的文章数量,然后保存。
如果你只需要简单的调用最新文章并显示标题和链接,可以使用以下简单的代码:
<?php$recent_posts = wp_get_recent_posts(array( 'numberposts' => 5, // 显示最近5篇文章 'post_status' => 'publish' // 仅显示已发布的文章 ));foreach ($recent_posts as $post) : ?> <div class="latest-post"> <h2><a href="<?php echo get_permalink($post['ID']); ?>"><?php echo $post['post_title']; ?></a></h2> </div> <?phpendforeach; ?>
WP_Query
提供了最大的灵活性,可以根据你设置的参数进行复杂查询。
get_posts()
是一种更简洁的方式,适合简单查询。
wp_get_recent_posts()
是最简洁的方式,用于直接获取最新文章。
复制本文链接开发笔记文章为老站长说所有,未经允许不得转载。