这个都是原来的老代码了,一直在用,刚刚看到留言有人需要,做个整理,给有需要的朋友!随机打开一篇文章,也就是我这里的“手气不错“,当时想到这个是因为google的首页上有这么个按钮,便也用这个了;该方法的实现有好几种,这里用functions.php的简洁方法。

我用的方法:把以下代码放到functions.php的最后一个?>前:

function random_postlite() {
	global $wpdb;
	$query = "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_password = '' AND 	post_status = 'publish' ORDER BY RAND() LIMIT 1";
	if ( isset( $_GET['random_cat_id'] ) ) {
		$random_cat_id = (int) $_GET['random_cat_id'];
		$query = "SELECT DISTINCT ID FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id AND tr.term_taxonomy_id = $random_cat_id) INNER JOIN  $wpdb->term_taxonomy AS tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id AND taxonomy = 'category') WHERE post_type = 'post' AND post_password = '' AND 	post_status = 'publish' ORDER BY RAND() LIMIT 1";
	}
	if ( isset( $_GET['random_post_type'] ) ) {
		$post_type = preg_replace( '|[^a-z]|i', '', $_GET['random_post_type'] );
		$query = "SELECT ID FROM $wpdb->posts WHERE post_type = '$post_type' AND post_password = '' AND 	post_status = 'publish' ORDER BY RAND() LIMIT 1";
	}
	$random_id = $wpdb->get_var( $query );
	wp_redirect( get_permalink( $random_id ) );
	exit;
}
if ( isset( $_GET['random'] ) )
add_action( 'template_redirect', 'random_postlite' );

然后在导航栏添加该链接:

<a href="<?php echo get_option('home') ?>/?random" title="随机推荐一篇文章给你!">手气不错</a>

还有其他好几种方法,这里只是一种;
完。