php列表改为随机加载

php列表顺序加载改为随机加载

        <div class="tab-list active">
            <ul class="post-loop post-loop-default cols-4">
                <?php
                $exclude = isset($options['newest_exclude']) && is_array($options['newest_exclude']) ? $options['newest_exclude'] : array();
                $arg = array(
                    'posts_per_page' => $per_page,
                    'ignore_sticky_posts' => 0,
                    'post_type' => 'post',
                    'post_status' => array( 'publish' ),
                    'category__not_in' => $exclude
                );
                $posts = new WP_Query($arg);
                if( $posts->have_posts() ) { while ( $posts->have_posts() ) { $posts->the_post(); ?>
                    <?php get_template_part( 'templates/loop' , 'default-sticky' ); ?>
                <?php } } wp_reset_postdata(); ?>
            </ul>
            <?php if($posts->max_num_pages>1){ ?>
                <div class="load-more-wrap">
                    <div class="btn load-more j-load-more" data-per_page="<?php echo $per_page;?>" data-exclude="<?php echo implode(',', $exclude);?>"><?php _e('Load more posts', 'wpcom');?></div>
                </div>
            <?php } ?>
        </div>

shuffe()函数 ,打乱数组中的元素位置

 $arr = [1, 2, 3, 4, 5];
 var_dump( shuffle( $arr ) ) ;
 print_r( $arr );
  • 定义随机数组,随机数组的值,与列表数据量相同
  • 比如列表有10条数据,就生成一个09的数组,数组里面的值是09但是随机顺序
  • 然后遍历这个随机数组,从列表中取对应下标的数据

如有帮助,请采纳,十分感谢!