在wordpress中要随机显示文章我们给大家介绍了三种调用随机文章的方法,有需要的朋友可根据自己的需要选择一种即可.
方法一:采用wordpress内置函数,在需要的时候直接调用以下代码:
- <ul>
- <?php $rand_posts = get_posts('numberposts=5&orderby=rand');
- foreach( $rand_posts as $post ) : ?>
- <li>
- <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
- </li>
- <?php endforeach; ?>
- </ul>
方法二:用query_posts生成随机文章列表,代码如下:
- <?php
- query_posts('showposts=10&orderby=rand');
- if ( have_posts() ) : while ( have_posts() ) : the_post();
- ?>
- <li><em><?php echo $j++;?></em><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
- <?php
- endwhile; else:
- ?>
没有可显示的文章,代码如下:
- <?php
- endif;
- wp_reset_query();
- ?>
方法三:在函数模版function.php中添加函数,然后调用,在function.php文件中添加以下代码:
- function random_posts($posts_num=8,$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;
- }//random_posts()参数有$posts_num即文章数量,$before开始标签默认<li>,$after=结束标签默认</li>
然后在需要调用随机文章的地方插入下面的代码:
- <div class="right">
- <h3>随便找点看看!</h3>
- <ul>
- <?php random_posts(); ?>
- </ul>
- </div>
新闻热点
疑难解答
图片精选