最近有一个需求,想在首页获取置顶过的文章和最新发布的文章,最新发布的文章是要排除一些栏目的,于是乎网上搜索资料,成功实现自己想要的功能,在此自己也简单整理记录一下。
获取网站置顶文章代码:
<?php $sticky = get_option('sticky_posts'); rsort( $sticky );
$sticky = array_slice( $sticky, 0, 2);query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) );
if (have_posts()) :while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank">
<?php the_title(); ?>
</a>
</li>
<?php endwhile; endif; ?>
获取发布的最新文章代码:
<?php $post_query = new WP_Query('cat=1,2,5,6,7,8,9,10&showposts=2'); //获取栏目id为1,2,5,6,7,8,9,10的最新两条最新文章
while ($post_query->have_posts()) : $post_query->the_post();$do_not_duplicate = $post->ID; ?>
<li>
<a href="<?php the_permalink(); ?>" target="_blank">
<?php if ( has_post_thumbnail() ) : ?>
<?php the_post_thumbnail(); ?>
<?php else : ?>
<img src="<?php bloginfo('template_url'); ?>/images/thumb.png">
<?php endif; ?><div class="title"><p><?php the_title(); ?></p></div>
</a>
</li>
<?php endwhile;?>
如果想排除某个栏目,可以在栏目前添加减号cat=-4,表示去除掉id为4的栏目的内容。
那么如何查看栏目的id?
我们可以在分类栏目里,用鼠标放在栏目名字上,在左下角,就会出现栏目的ID了,如图所示:
