wordpress随机调用显示文章的方法

作者:袖梨 2022-06-25

方法一:采用wordpress内置函数,在需要的时候直接调用以下代码:

 代码如下 复制代码


  • <?php $rand_posts = get_posts('numberposts=5&orderby=rand');

foreach( $rand_posts as $post ) : ?>
  
        <?php the_title(); ?>
  
<?php endforeach; ?>

方法二:用query_posts生成随机文章列表。

 代码如下 复制代码

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


方法三:在函数模版function.php中添加函数,然后调用。
在function.php文件中添加以下代码:

 代码如下 复制代码

function random_posts($posts_num=8,$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;
}//random_posts()参数有$posts_num即文章数量,$before开始标签默认,$after=结束标签默认

然后在需要调用随机文章的地方插入下面的代码:

 代码如下 复制代码


   

随便找点看看!


   

  •         <?php random_posts(); ?>

  •    

相关文章

精彩推荐