WordPress如何调用全站随机文章/同分类随机文章

看过上一篇WordPress教程的朋友应该已经学会如何调用最新文章、热门文章以及指定分类文章了,但是我们也许会用到更多的调用文章方式,例如:调用随机文章,那么我们改如何调用到全部文章进行随机显示,或者是调用同一个分类下的随机文章呢?

下面给大家带来一篇WordPress教程,看完你就明白了!

整站随机文章

//numberposts 为文章数量

<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>

<a href="<?php the_permalink(); ?>" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" ><?php the_title(); ?></a>

<?php endforeach; ?>

同分类随机文章

<?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" ><?php the_title(); ?></a>

<?php endwhile;?>
<?php wp_reset_query(); ?>

是不是很简单呢?只需要在需要调用随机文章的页面,加入上面任意一种代码即可!

0
0