WordPress 调用同分类或指定某分类下的随机文章

WordPress教程 3499

给客户制作wordpress主题的时候需要调用文章内容页同分类下的随机文章或网站指定分类的随机文章,后者通过query_posts()函数很容易就可以实现调用(参考wordpress query_posts()函数介绍),前者通过获取同分类ID后也可以很简单地实现调用。

调用同分类下的随机文章:添加到与文章内容页相关的模板,如single.php

1
2
3
4
5
6
7
8
9
10
11
12
<?php
    $cat = get_the_category();
    foreach($cat as $key=>$category){
		$cat_id = $category->term_id;
    }
    $args = array('orderby' => 'rand','showposts' => 10,'cat' => $$cat_id );
    $query_posts = new WP_Query();
    $query_posts->query($args);
    while ($query_posts->have_posts()) : $query_posts->the_post();
?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
  • showposts后面的 10 是显示的文章数量

调用指定分类下的随机文章:

1
2
3
4
5
6
<?php 
	query_posts('showposts=10&cat=1&orderby=rand');
	while(have_posts()) : the_post();
?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>
  • showposts后面的 10 是调用的文章数量
  • cat后面的 1 是要调用的分类ID

修改上面对应的参数就可以了!

精品推荐: