置顶文章是指文章将被放在文章首页的顶部,这个功能只适用于内置的文章类型,不适用自定义的文章类型。
如何置顶文章
- 进入管理界面>文章>添加新的或编辑
- 在右侧栏中,单击“发布”组中“可见性”选项的编辑链接
- 点击“将文章置于首页顶端”选项
显示置顶文章
展示置顶文章
只显示第一篇置顶文章,至少有一篇文章必须被置顶,否则循环将显示所有文章:
$sticky = get_option( 'sticky_posts' ); $query = new WP_Query( 'p=' . $sticky[0] );
只显示第一篇置顶文章,如果没有则返回最后发布的文章:
$args = array( 'posts_per_page' => 1, 'post__in' => get_option( 'sticky_posts' ), 'ignore_sticky_posts' => 1 ); $query = new WP_Query( $args );
只显示第一篇置顶文章,如果没有,则不返回:
$sticky = get_option( 'sticky_posts' ); $args = array( 'posts_per_page' => 1, 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ); $query = new WP_Query( $args ); if ( isset( $sticky[0] ) ) { // insert here your stuff... }
不展示置顶文章
从查询中排除所有置顶文章:
$query = new WP_Query( array( 'post__not_in' => get_option( 'sticky_posts' ) ) );
从某个类别中排除置顶文章,返回该类别中的所有文章,但不在顶部显示置顶文章。其他地方的置顶文章仍将显示(例如,按日期):
$query = new WP_Query( 'ignore_sticky_posts=1&posts_per_page=3&cat=6' );
从某个类别中排除置顶文章,返回该类别中的所有文章但完全不包括置顶文章,并遵守分页规则:
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $sticky = get_option( 'sticky_posts' ); $args = array( 'cat' => 3, 'ignore_sticky_posts' => 1, 'post__not_in' => $sticky, 'paged' => $paged ); $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)