wordpress调用指定分类文章
wordpress是很强大的cms系统,你可以通过相关函数就能实现相关的功能。WordPress如何调用指定分类目录文章?
首页调用指定分类文章
如果是博客网站,首页的文章通常是全站的,想调用指定分类,参考下面的代码
<ul>
<?php
$args=array(
'cat' => 1, // 分类ID
'posts_per_page' => 10, // 显示篇数
);
query_posts($args);
if(have_posts()) : while (have_posts()) : the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> //标题
<span>
<?php if (has_excerpt()) {
echo $description = get_the_excerpt(); //文章编辑中的摘要
}else {
echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 170,"……"); //文章编辑中若无摘要,自定截取文章内容字数做为摘要
} ?>
</span>
</li>
<?php endwhile; endif; wp_reset_query(); ?>
</ul>
$args:是要显示的分类的参数。
query_posts():可以用来控制在循坏(Loop)中显示哪些文章。
下面的添加循环和条件判断,还有标题,内容的输出 大家应该知道了。
另外一种方法,在functions.php添加代码
//functions.php修改,这个方法是比较好的,建议使用。
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-240, -327' ); //你要排除的分类ID
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
-240和-327 是我分类ID。修改你要调用的即可。
cms方式调用指定分类文章
比如我想在首页调用指定分类的文章显示在某个位置,数量10篇,这时候就要用到WP_Query
WP_Query是wordpress提供的一个类,它支持的参数非常完善灵活,博主通过WP_Query类可以创建自己所需要的wordpress循环输出,比如调用最新文章、热门文章、自定义文章类型文章循环输出等,和query_posts()函数具有相同的查询功能,但优于query_posts()函数。
<?php
$args = array(
// 用于查询的参数或者参数集合
);
// 自定义查询
$the_query = new WP_Query( $args );
// 判断查询的结果,检查是否有文章
if ( $the_query->have_posts() ) :
// 通过查询的结果,开始主循环
while ( $the_query->have_posts() ) :
$the_query->the_post(); //获取到特定的文章
// 要输出的内容,如标题、日期等
endwhile;
endif;
// 重置请求数据
wp_reset_postdata();
?>
<?php
$args = array('post_type'=>'post','showposts'=>'10','posts_per_page'=>'10','paged'=>get_query_var('paged'));
$recendposts = new WP_Query( $args );
if($recendposts->have_posts()) :
while($recendposts->have_posts()) :
$recendposts->the_post();
?>
<li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
写笔记