鱼见海资源网最新教程:
制作WordPress主题经常要调用不同的文章列表,随机文章就是调用文章列表的一种。实现调用随机文章的方式主要有两类,一种方式是直接通过插件来实现,另外一种就是使用代码实现。本文就分享五种不用插件调用随机文章的方法,主要是将排序orderby的值设置成rand参数。这种方式不仅增强用户粘性,而且当蜘蛛来爬取文章的时候每次都会有变化,搜索引擎很喜欢。

1.最直接的用法,在需要的位置放入下面的代码。
5, 'orderby' => 'rand', 'post_status' => 'publish' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
2.用query_posts生成随机文章列表
'rand', 'showposts' => 2));
if (have_posts()) :
while (have_posts()) : the_post();?>
'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
the_title(); //这行去掉就不显示标题
the_excerpt(); //去掉这个就不显示摘要了
endwhile;
endif; ?>
3.调用同分类随机文章
$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();
?>
4.用wp_query函数
'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();
?>
5.主题function定义
//随机文章
function random_posts($posts_num=5,$before='',$after=' '){
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.'' . $post_title . '';
$output .= $after;
}
echo $output;
}
在需要显示随机文章的地方加入如下代码
随便找点看看!
文章来源于互联网
© 版权声明
温馨提示:本站知识付费,提供的一切软件、教程和内容信息都来自网络收集整理,仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负,版权争议与本站无关。用户必须在下载后的24个小时之内,从您的电脑或手机中彻底删除上述内容。如果您喜欢该程序和内容,请支持正版,购买注册,得到更好的正版服务。我们非常重视版权问题,如有侵权请邮件与我们联系处理。敬请谅解!
THE END
暂无评论内容