探索建站和运维乐趣

WordPress无需插件即可实现调用分类和随机文章方式

我们在设计和制作WordPress主题的时候,有些模块我们没有不要通过特别复杂的后端和插件设置,我会将客户的需求设置在模板里直接调用。比如我们的企业网站客户经常需要在侧边空缺的位置补全不至于空,我会调用随机文章和企业新闻类的内容,这个我一般采用直接SQL代码调用全文内容。

第一、随机文章内容

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

我们可以设置调出数量,以及样式微调整,将代码添加到需要的位置。

第二、随机分类文章

以上是随机文章是全站内容,如果我们需要调用某个分类内容。比如我们企业网站肯定要指定特殊的分类内容,不能将其他内容调出来,比较难看。

// 随机某个分类的随机文章 Edit By laobuluo.com
<?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();?>
<a href="<?php the_permalink(); ?>" rel="external nofollow"  rel="external nofollow" ><?php the_title(); ?></a>
<?php endwhile;?>
<?php wp_reset_query(); ?>

同样的,我们可以添加到需要调用的位置。可以实现随机指定分类内容的随机文章内容调出。

赞(1)
转载保留:老部落 » WordPress无需插件即可实现调用分类和随机文章方式


关注公众号『老蒋朋友圈』

获取更多建站运营运维新知!
互联网创业、前沿技术......