简体   繁体   中英

Posts not being ordered randomly

I'm trying to have random posts appear in this post loop:

首页帖子循环截图

Even though I've added 'orderby' => 'rand', it still displays the same 4 posts always. Here's my complete code for the post loop:

$query = new WP_Query(array(
'post_status'   => 'publish',
'orderby'       => 'title',
'orderby' => 'rand',
'cat' => '3',
'order'         => 'ASC',
'posts_per_page'    => 4
));
$post_count = $query->post_count;
$posts_per_column = ceil($post_count / 4);
$rows = array();
$count = 0;
while ($query->have_posts())
{ $query->the_post();
if($rows[$count] == ""){ $rows[$count] = ''; }
            $rows[$count] = $rows[$count] . '<div class="col-post"><div class="post-title"><a href="'.get_permalink().'">'.get_the_title().'</a></div></div>';
                                            $count++;
                                            if ($count == $posts_per_column ) { $count = 0; }
                                            }
                            foreach ($rows as $row) { echo $row . ''; }
        wp_reset_query();

You're currently running two orderby arguments, which cause one of them to be ignored. You do understand that ordering by 'orderby' => 'title', AND 'orderby' => 'rand', are not compatible.

The following should work:

$query = new WP_Query( array(
  'post_status' => 'publish',
  'orderby' => 'RAND',
  'cat' => '3',
  'posts_per_page' => 4
) );

orderby (string | array)

Sort retrieved posts by parameter. Defaults to 'date (post_date)'. One or more options can be passed.
...
'rand' – Random order.
'title' – Order by title.

Furthermore, the 'order' => 'ASC', is not required (It's just getting ignored, you're pasing and argument for nothing wich slows the query) as you're using 'orderby' => 'RAND', , by default the value is set to 'orderby' => 'DESC',

order (string | array)

Designates the ascending or descending order of the 'orderby' parameter. Defaults to 'DESC'. An array can be used for multiple order/orderby sets.
'ASC' – ascending order from lowest to highest values (1, 2, 3; a, b, c).
'DESC' – descending order from highest to lowest values (3, 2, 1; c, b, a).

Source @ https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM