在WordPress網(wǎng)站開發(fā)中,經(jīng)常需要突出顯示某些重要內(nèi)容,置頂文章(Sticky Posts)功能就是為此設(shè)計的。本文將詳細(xì)介紹如何在WordPress中調(diào)用和顯示置頂文章。
什么是置頂文章
置頂文章是WordPress提供的一種特殊文章類型,它們會始終顯示在博客文章列表的最前面,無論其發(fā)布時間如何。這個功能特別適合用來展示公告、重要消息或特色內(nèi)容。
基本調(diào)用方法
使用WP_Query調(diào)用置頂文章是最常見的方法:
<?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();
// 顯示文章內(nèi)容
the_title();
the_excerpt();
}
}
wp_reset_postdata();
?>
進(jìn)階使用方法
1. 調(diào)用置頂文章并排除非置頂文章
<?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);
// 循環(huán)輸出
}
?>
注意事項
- 當(dāng)沒有置頂文章時,
get_option('sticky_posts')
會返回空數(shù)組,需要做判斷處理 - 使用
ignore_sticky_posts
參數(shù)可以控制是否忽略置頂文章的默認(rèn)排序行為 - 在多站點WordPress中,置頂文章設(shè)置是站點獨立的
- 置頂文章功能只對標(biāo)準(zhǔn)文章(post)類型有效
主題集成建議
為了更好的用戶體驗,建議在主題開發(fā)時:
- 為置頂文章添加特殊樣式類名,如
.sticky-post
- 在文章循環(huán)前先檢查是否有置頂文章
- 考慮移動端顯示效果
- 提供置頂文章數(shù)量控制選項
通過以上方法,您可以靈活地在WordPress網(wǎng)站中調(diào)用和展示置頂文章,提升重要內(nèi)容的曝光率。