wordpress显示随机文章实现方法

作者:袖梨 2022-06-25

首页随机显示文章 在wordpress里面并不难,也不需要安装复杂的插件,只需要在合适的php文件里面添加如下代码,这个完全归功于wordpress的模块化结构,代码如下

1.使用get_posts生成随机文章

 代码如下 复制代码

<?php
$rand_posts = get_posts('numberposts=10&orderby=rand');
foreach( $rand_posts as $post ) :
?>

<?php the_title(); ?>
<?php endforeach; ?>


2.使用随处可见的query_psots

 代码如下 复制代码

<?php
query_posts('showposts=10&orderby=rand');
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>

<?php echo $j++;?><?php the_title(); ?>
<?php
endwhile; else:
?>
没有可显示的文章
<?php
endif;
wp_reset_query();
?>

3.自定随机文章显示

 代码如下 复制代码

   


  •     <?php

  •     $args = array( 'numberposts' => 5, 'orderby' => 'rand' );

  •     $rand_posts = get_posts( $args );

  •     foreach( $rand_posts as $post ) : ?>

  •        
  • <?php the_title(); ?>

  •     <?php endforeach; ?>

  •    

相关文章

精彩推荐