在平時我們用wordpress系統進行網站開發時,經常會用到隨機調用數據信息的需求。這樣對于我們頁面或是詳細頁中,這樣每次訪問時就會展示不同的數據,每次都會更新不同的數據,這樣可以給網站用戶訪問一種每次不同的訪問變化與數據展示。
1、最常見的調用隨機代碼,這樣也比較容易懂,調用數據也比較簡單。
<?php $args?=?array(?'events'?=> 5,?'orderby'?=>?'rand',?'post_status'?=>?'publish'?); $rand_posts?= get_posts(?$args?); foreach(?$rand_posts?as?$post?) : ?> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> <?php?endforeach; ?>
2、也可以采用 query_posts 生成隨機文章列表,但是這種一般只應用于 post 常規組件調用。
<?php $args?=?array(?'events'?=> 5,?'orderby'?=>?'rand',?'post_status'?=>?'publish'?); $rand_posts?= get_posts(?$args?); foreach(?$rand_posts?as?$post?) : ?> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> <?php?endforeach; ?>
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(); ?> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> <?php endwhile;?> <?php wp_reset_query(); ?>