隨機文章如果單條sql是非常的簡單直接使用rand就可以得到了,但是在wordpress中我們需要稍加處理即可了,下面我總結了一些方法,希望對各位有幫助.
調用隨機文章代碼:
- <?php
- $rand_posts = get_posts(‘numberposts=10&orderby=rand’);
- foreach( $rand_posts as $post ) :
- ?>
- <!–下面是你想自定義的Loop–>
- <li><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></li>
- <?php endforeach; ?>
調用相關文章代碼,在文章頁顯示相關文章,代碼如下:
- <?php
- $tags = wp_get_post_tags($post->ID);
- if ($tags) {
- $first_tag = $tags[0]->term_id;
- $args=array(‘
- tag__in’ => array($first_tag),
- ‘post__not_in’ => array($post->ID),
- ‘showposts’=>10,
- ‘caller_get_posts’=>1
- );
- $my_query = new WP_Query($args);
- if( $my_query->have_posts() ) {
- while ($my_query->have_posts()) : $my_query->the_post(); ?>
- <li><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”<?php the_title_attribute(); ?>”><?php the_title();?> <?php comments_number(‘ ‘,’(1)’,’(%)’); ?></a></li>
- <?php
- endwhile;
- }
- }
- wp_reset_query();
- ?>
調用同分類隨機文章,將下面代碼放到主題文章頁面single模板或者邊欄sidebar模板適當位置即可:
- <ul>
- <?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;?>
- </ul>
新聞熱點
疑難解答
圖片精選