之前 有个主题 分享了调用最新文章、调用热门文章、调用指定分类文章,那么我开wordpress开发中如何调用随机文章呢?
下面分享五种wordpress随机文章调用方法
一:最直接的用法
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>" rel="external nofollow" ><?php the_title(); ?></a></li>
<?php endforeach; ?>
使用方法:在需要的位置放入下面的代码。
二:用query_posts生成随机文章列表
<?php
query_posts(array('orderby' => 'rand', 'showposts' => 2));
if (have_posts()) :
while (have_posts()) : the_post();?>
<a href="<?php the_permalink() ?>" rel="external nofollow" rel="bookmark"><?php the_title(); ?></a>
<?php endwhile; ?>
<?php endif; ?>
<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
the_title(); //这行去掉就不显示标题
the_excerpt(); //去掉这个就不显示摘要了
endwhile;
endif; ?>
三:主题function定义
首先在主题的function.php文件中添加下面代码:
/**
* 随机文章
*/
function random_posts($posts_num=5,$before='<li>',$after='</li>'){
global $wpdb;
$sql = "SELECT ID, post_title,guid
FROM $wpdb->posts
WHERE post_status = 'publish' ";
$sql .= "AND post_title != '' ";
$sql .= "AND post_password ='' ";
$sql .= "AND post_type = 'post' ";
$sql .= "ORDER BY RAND() LIMIT 0 , $posts_num ";
$randposts = $wpdb->get_results($sql);
$output = '';
foreach ($randposts as $randpost) {
$post_title = stripslashes($randpost->post_title);
$permalink = get_permalink($randpost->ID);
$output .= $before.'<a href="'
. $permalink . '" rel="bookmark" title="';
$output .= $post_title . '">' . $post_title . '</a>';
$output .= $after;
}
echo $output;
}
然后在想要显示随机文章的地方加入如下代码
<div class="right">
<h3>随机文章</h3>
<ul>
<?php random_posts(); ?>
</ul>
</div><!-- 随机文章 -->
以上就是三种全站随机文章的方法了,不知道你学会了没?
下面这篇文章讲解了如何调用同分类随机文章,感兴趣的朋友可以看看。