A Sticky Post 是指置顶文章,该文章将显示在帖子首页的顶部。此功能仅适用于内置的文章类型(post),不适用于自定义文章类型。

如何置顶文章

  1. 进入后台管理界面 > 文章 > 添加新文章或编辑
  2. 在右侧菜单中,点击“发布”组中的可见性选项的“编辑”链接
  3. 点击“将此帖子置顶到首页”选项

显示置顶文章

显示置顶文章

仅显示第一个置顶文章。必须至少有一篇文章被指定为“置顶文章”,否则循环将显示所有文章:

<?php
$sticky = get_option( 'sticky_posts' );
$query  = new WP_Query( 'p=' . $sticky[0] );

仅显示第一个置顶文章,如果没有则返回最近发布的文章:

<?php
$args  = array(
	'posts_per_page'      => 1,
	'post__in'            => get_option( 'sticky_posts' ),
	'ignore_sticky_posts' => 1,
);
$query = new WP_Query( $args );

仅显示第一个置顶文章,如果没有则不返回任何内容:

<?php
$args   = array(
	'posts_per_page'      => 1,
	'post__in'            => get_option( 'sticky_posts' ),
	'ignore_sticky_posts' => 1,
);
$query  = new WP_Query( $args );
if ( isset( $sticky[0] ) ) {
	// Insert here your stuff...
}

不显示置顶文章

从查询中排除所有置顶文章:

<?php
$args  = array( 'post__not_in' => get_option( 'sticky_posts' ) );
$query = new WP_Query( $args );

从类别中排除置顶文章。返回该类别中的所有帖子,但不将置顶文章显示在顶部。“置顶文章”仍会以其自然位置(例如按日期)显示:

<?php
$args  = array(
	'ignore_sticky_posts' => 1,
	'posts_per_page'      => 3,
	'cat'                 => 6,
);
$query = new WP_Query( $args );

从类别中排除置顶文章。返回该类别中的帖子,但完全排除置顶文章,并遵守分页规则:

<?php
$args  = array(
	'cat'                 => 3,
	'ignore_sticky_posts' => 1,
	'post__not_in'        => get_option( 'sticky_posts' ),
	'paged'               => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
);
$query = new WP_Query( $args );
如果您希望此查询在您将其设置为静态首页的页面模板中工作,请使用 get_query_var(‘page’)。
<?php
/* Get all Sticky Posts */
$sticky = get_option( 'sticky_posts' );

/* Sort Sticky Posts, newest at the top */
rsort( $sticky );

/* Get top 5 Sticky Posts */
$sticky = array_slice( $sticky, 0, 5 );

/* Query Sticky Posts */
$query = new WP_Query( array(
	'post__in'            => $sticky,
	'ignore_sticky_posts' => 1,
) );

样式化置顶文章

为了帮助主题作者进行更简单的样式设置,post_class()函数用于向 DIV 添加 class="...",只需:

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

post_class()为该 div 输出 class="whatever"部分。其中包括几种不同价值的类:post、hentry(用于 hAtom 微格式页面)、category-X(其中 X 是帖子所在每个类别的 slug),以及 tag-X(类似,但针对标签)。它还添加了“sticky”,以标记为置顶文章的帖子。

.sticky { color: red; }
“sticky”类仅在首页的第一页上的置顶文章中添加(is_home() 为 true 且 is_paged() 为 false)