1. 程式人生 > 實用技巧 >五個wordpress呼叫隨機文章的方法

五個wordpress呼叫隨機文章的方法

分享幾個WordPress不用外掛呼叫隨機文章的方法,不僅增強使用者粘性,而且當蜘蛛來爬你的文章的時候每次都會有變化,搜尋引擎很喜歡。主要用到的是orderby rand引數,下面就隨ytkah一起來看看吧

  1、最直接的用法,在需要的位置放入下面的程式碼。

1 2 3 4 5 6 <?php $args=array('numberposts'=> 5,'orderby'=>'rand','post_status'=>'publish'); $rand_posts= get_posts($args); foreach($rand_postsas$post
) : ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?phpendforeach; ?>

  2、用query_posts生成隨機文章列表

1 2 3 4 5 6 7 <?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> <?phpendwhile; ?> <?phpendif; ?>

  

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

  3、呼叫同分類隨機文章

1 2 3 4 5 6 7 8 9 10 11 12 13 <?php $cat= get_the_category(); foreach($catas$key=>$category){ $catid=$category->term_id; } $args=array('orderby'=>'rand','showposts'=> 8,'cat'=>$catid); $query_posts=newWP_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> <?phpendwhile;?> <?php wp_reset_query(); ?>

  4、用wp_query函式

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?php $args=array( 'post_type'=>'post', 'showposts'=> 4, 'orderby'=>'rand', 'cat'=> -36,//除了id為36的分類 ); $my_query=newWP_Query($args); if($my_query->have_posts() ) { while($my_query->have_posts()) :$my_query->the_post(); ?> <divclass="item"> <a href="<?php the_permalink(); ?>"class="box"> <?php the_post_thumbnail(array(285,360) ); ?> <divclass="text"> <strong><?php the_title();?></strong> </div> </a> </div> <?phpendwhile; wp_reset_query(); } ?>

  

  5、主題function定義

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /** * 隨機文章 */ functionrandom_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($randpostsas$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; }

  然後在想要顯示隨機文章的地方加入如下程式碼

1 2 3 4 5 6 <divclass="right"> <h3>隨便找點看看!</h3> <ul> <?php random_posts(); ?> </ul> </div><!-- 隨機文章 -->