之前 有个主题 分享了三种调用全站随机文章的方法,后来群里有小伙伴问如何调用同分类的随机文章呢?
嗯,也很简单的,下面两种方法都可行。
方法一:
<?php
$cat = get_the_category();
foreach($cat as $key=>$category){
$catid = $category->term_id;}
$args = array('orderby' => 'rand','showposts' => 8,'cat' => $catid ); // 显示文章篇数
$query_posts = new WP_Query();
$query_posts->query($args);
while ($query_posts->have_posts()) : $query_posts->the_post();?>
<a href="<?php the_permalink(); ?>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><?php the_title(); ?></a>
<?php endwhile;?>
<?php wp_reset_query(); ?>
方法二
<?php
$args = array(
'post_type' => 'post',
'showposts' => 4,
'orderby' => 'rand',
'cat' => -36,//除了id为36的分类
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="item">
<a href="<?php the_permalink(); ?>" rel="external nofollow" rel="external nofollow" class="box">
<?php the_post_thumbnail( array(285,360) ); ?>
<div class="text">
<strong><?php the_title();?></strong>
</div>
</a>
</div>
<?php endwhile; wp_reset_query(); } ?>