Wordpress 调用随机文章的方法

1、最直接的用法,在需要的位置放入下面的代码。

<?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; ?>


2、用query_posts生成随机文章列表

<?php
query_posts(array('orderby' => 'rand', 'showposts' => 2));
if (have_posts()) :
  while (have_posts()) : the_post();?>
    <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>
  <?php endwhile; ?>
<?php endif; ?>

<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
the_title(); //这行去掉就不显示标题
the_excerpt(); //去掉这个就不显示摘要了
endwhile;
endif; ?>


3、调用同分类随机文章

<?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(); ?>


修改时间 2023-11-14

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
随机推荐
JavaScript 原生拖放
CRSF 跨站脚本攻击已死,使用 Same-Site Cookies 来防范 CSRF
WordPress 常用接口
HTML 对话框元素 dialog
MySQL 使用 DATE_FORMAT() 和 FROM_UNIXTIME() 格式化时间
Node.js 18.x 开始支持内置单元测试
WordPress 添加 Favicon 图标的方法
使用 svg 作为背景图片