设为首页 - 加入收藏
广告 1000x90
您的当前位置:主页 > 自媒体运营 > 正文

wordpress实现调用相同分类下随机文章代码

来源:网络分享 编辑:引流技巧 时间:2025-05-14

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;?>     <?php wp_reset_query(); ?> </ul>

如果是需要不同分类随机文章 ,则可用如下代码

<ul> <?php $args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish' ); $rand_posts = get_posts( $args ); foreach( $rand_posts as $post ) : ?>     <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> </ul>

这样就能得到随机排序(第 2 个参数)的已发布(第 3 个参数)文章中的 5 篇(第 1 个参数)。

需要特别注意的是,如果没有第 3 个参数,它可能会将草稿之类的文章也显示出来。

相关推荐:

栏目分类

微商引流技巧网 www.yinliujiqiao.com 联系QQ:1716014443 邮箱:1716014443@qq.com

Copyright © 2019-2024 强大传媒 网站地图 rss地图

Top