WordPress實(shí)現(xiàn)讓訪客隨機(jī)查看文章功能
來源:程序員人生 發(fā)布時(shí)間:2014-02-07 16:24:03 閱讀次數(shù):3692次
WordPress現(xiàn)在使用于各種各樣的網(wǎng)站,博客,商務(wù)站,論壇站等等,功能強(qiáng)大地球人都知道,就不贅述了。分享一段代碼,可以把訪客轉(zhuǎn)到隨機(jī)文章的頁(yè)面。
首先把下面這段代碼添加到functions.php中。
add_action('init','random_add_rewrite');
function random_add_rewrite() {
global $wp;
$wp->add_query_var('random');
add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
}
add_action('template_redirect','random_template');
function random_template() {
if (get_query_var('random') == 1) {
$posts = get_posts('post_type=post&orderby=rand&numberposts=1');
foreach($posts as $post) {
$link = get_permalink($post);
}
wp_redirect($link,307);
exit;
}
}
然后創(chuàng)建一個(gè)頁(yè)面鏈接為http://yourdomain.com/random 。當(dāng)用戶點(diǎn)擊之后就被轉(zhuǎn)接到你博客的隨機(jī)文章頁(yè)面。
另外如果你使用W3 Total Cache插件了的話,要在exclude list添加以下代碼才能成功。
/random/
/index.php?random=1