在使用 WordPress 建站過程中,為了使得整個網站得頁面更加豐富,或者使網站具有更強的用户粘度,我們通常會需要在頁面展示一些隨機文章,這樣也可以使得文章的 pv 得到提升。 (查看 WordPress 獲取隨機文章 (插件版本))
WordPress 獲取隨機文章方法無法兩種:

WordPress 教程網比較推崇自己寫代碼,大家都知道插件過多必然影響到網站得性能。

方法一:自己編寫代碼
1 、在你的主題 functions.php 文件添加如下代碼:

/**
 * WordPress 教程網 (wpnoob.cn)
 * 隨機文章
 */
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="http://'.%20$permalink%20.%20'"  rel="bookmark" title="';
		$output .= $post_title . '">' . $post_title . '</a>';
		$output .= $after;
	}
	echo $output;
}

在需要顯示的地方調用如下代碼

<div >
	<h3> 我猜你喜歡</h3>
	<ul>
		<?php random_posts(); ?>
	</ul>
</div><!-- 隨機文章 -->

很簡單吧!!!何必用啥插件哈!!

方法二:代碼最簡單的方法
在需要顯示隨機文章地方添加如下代碼:

<ul>
<?php $rand_posts = get_posts('numberposts=5&orderby=rand');
foreach( $rand_posts as $post ) : ?>
   <li>
        <a href="<?php%20the_permalink();%20?>"><?php the_title(); ?></a>
   </li>
<?php endforeach; ?>
</ul>

這個方法雖然簡單,但用到了 get_posts,如果將代碼放在子頁模板裏,在他之後的代碼,比如如果在後面同時調用了當前文章的評論,那評論內容很可能,出現的是最後一個隨機到的文章的評論,而非當前文章的評論。

方法三:用 query_posts 生成隨機文章列表
在需要顯示隨機文章地方添加如下代碼:

<?php
query_posts(array('orderby' => 'rand', 'showposts' => 2));
if (have_posts()) :
while (have_posts()) : the_post();?>
<a href="<?php%20the_permalink()%20?>"
	rel="bookmark"
	title=<?php the_title(); ?>"><?php the_title(); ?></a>&nbsp;
	<?php comments_number(", '(1)', '(%)'); ?>
<?php endwhile;endif; ?>

方法四:在隨機文章中顯示標題和文章摘要
在需要顯示隨機文章地方添加如下代碼:

<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
the_title(); //這行去掉就不顯示標題
the_excerpt(); //去掉這個就不顯示摘要了
endwhile;
endif;
?>

方法總結:
除了我再用的第一種方法,其他三種方法中都使用到了,get_posts 、 the_post 等方法,這些方法破壞頁面中記錄的當前文章的信息,如果使用在頁面的最後部分,影響不大,如果在調用的代碼後面還有評論等內容,則會導致評論內容調用的是隨機到的最後一篇文章的評論。