分享幾個WordPress不用插件調用隨機文章的方法,不只加強用戶粘性,並且當蜘蛛來爬你的文章的時候每次都會有變化,搜索引擎很喜歡。主要用到的是orderby rand參數,下面就隨ytkah一塊兒來看看吧php
一、最直接的用法,在須要的位置放入下面的代碼。sql
<?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(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?>
二、用query_posts生成隨機文章列表dom
<?php query_posts(array('orderby' => 'rand', 'showposts' => 2)); if (have_posts()) : while (have_posts()) : the_post();?> <a href="<?php the_permalink() ?>" 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; ?>
三、調用同分類隨機文章函數
<?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(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile;?> <?php wp_reset_query(); ?>
四、用wp_query函數post
<?php $args = array( 'post_type' => 'post', 'showposts' => 4, 'orderby' => 'rand', 'cat' => -36,//除了id爲36的分類 ); $my_query = new WP_Query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <div class="item"> <a href="<?php the_permalink(); ?>" class="box"> <?php the_post_thumbnail( array(285,360) ); ?> <div class="text"> <strong><?php the_title();?></strong> </div> </a> </div> <?php endwhile; wp_reset_query(); } ?>
五、主題function定義ui
/** * 隨機文章 */ 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><!-- 隨機文章 -->