在WordPress网站开发中,经常需要突出显示某些重要内容,置顶文章(Sticky Posts)功能就是为此设计的。本文将详细介绍如何在WordPress中调用和显示置顶文章。
什么是置顶文章
置顶文章是WordPress提供的一种特殊文章类型,它们会始终显示在博客文章列表的最前面,无论其发布时间如何。这个功能特别适合用来展示公告、重要消息或特色内容。
基本调用方法
使用WP_Query调用置顶文章是最常见的方法:
<?php
$sticky = get_option('sticky_posts');
$args = array(
'post__in' => $sticky,
'ignore_sticky_posts' => 1
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// 显示文章内容
the_title();
the_excerpt();
}
}
wp_reset_postdata();
?>
进阶使用方法
1. 调用置顶文章并排除非置顶文章
<?php
$args = array(
'posts_per_page' => 5,
'post__in' => get_option('sticky_posts'),
'ignore_sticky_posts' => 1
);
$sticky_posts = new WP_Query($args);
?>
2. 在首页显示置顶文章
<?php
if (is_home() && get_option('sticky_posts')) {
$sticky = get_option('sticky_posts');
$args = array(
'post__in' => $sticky,
'posts_per_page' => 3
);
$query = new WP_Query($args);
// 循环输出
}
?>
注意事项
- 当没有置顶文章时,
get_option('sticky_posts')
会返回空数组,需要做判断处理 - 使用
ignore_sticky_posts
参数可以控制是否忽略置顶文章的默认排序行为 - 在多站点WordPress中,置顶文章设置是站点独立的
- 置顶文章功能只对标准文章(post)类型有效
主题集成建议
为了更好的用户体验,建议在主题开发时:
- 为置顶文章添加特殊样式类名,如
.sticky-post
- 在文章循环前先检查是否有置顶文章
- 考虑移动端显示效果
- 提供置顶文章数量控制选项
通过以上方法,您可以灵活地在WordPress网站中调用和展示置顶文章,提升重要内容的曝光率。