在制作WordPress模板的时候,会经常需要调用一些随机的文章和热门文章。那么这些具体的代码有哪些呢?下面我们就来看看。
WordPress调用随机文章
方法1:采用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>
方法2:用query_posts生成随机文章列表
<ul> <?php global $post; $postid = $post->ID; $args = array( 'orderby' => 'rand', 'post__not_in' => array($post->ID), 'showposts' => 14); $query_posts = new WP_Query(); $query_posts->query($args); ?> <?php while ($query_posts->have_posts()) : $query_posts->the_post(); ?> <li> <a href=''<?php the_permalink(); ?>'' title=''<?php the_title_attribute(); ?>''> <?php the_title(); ?> </a> </li> <?php endwhile; else: ?> 没有可显示的文章 <?php endif; wp_reset_query(); ?> </ul>
方法3:在主题的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>
WordPress调用同分类下的随机文章
在内页里面的适当位置显示调用随机文章可以促进网站内链,增加文章阅读点击量,有利于SEO,网上大部分WordPress调用随机文章代码都是基于全站文章,这里发一个调用同分类随机文章的代码。
将下面代码放到主题文章页面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>
WordPress调用热门文章
<ul> <?php $post_num = 14; // 设置调用条数 $args = array( 'post_password' => '', 'post_status' => 'publish', // 只选公开的文章. 'post__not_in' => array($post->ID),//排除当前文章 'caller_get_posts' => 1, // 排除置頂文章. 'orderby' => 'comment_count', // 依評論數排序. 'posts_per_page' => $post_num ); $query_posts = new WP_Query(); $query_posts->query($args); while( $query_posts->have_posts() ) { $query_posts->the_post(); ?> <li> <a href=''<?php the_permalink(); ?>'' title=''<?php the_title(); ?>''> <?php the_title(); ?> </a> </li> <?php } wp_reset_query();?> </ul>
评论前必须登录!
注册