K
K
Kak_B_CTapou_Cka3ke2021-06-25 12:13:29
WordPress
Kak_B_CTapou_Cka3ke, 2021-06-25 12:13:29

How to shuffle recent posts in wordpress?

The entries are output as follows:

$args=array(
 'category__in' => $category_ids, 
 'post__not_in' => array($post->ID),
 'posts_per_page' => 10,
 'showposts'=>2, 
 'orderby'=>'date'
 );


And you need to do it according to the following logic: we get the last 10 records by date and from them we display 2 randomly. How would it be implemented?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2021-06-25
@Kak_B_CTapou_Cka3ke

$posts = get_posts( array(
  'category__in' => $category_ids, 
  'post__not_in' => array($post->ID),
  'posts_per_page' => 10,
  'orderby' => 'date'
) );

// получаем два случайных ключа из массива
$rand_keys = array_rand($posts, 2);

foreach ( $posts as $key => $post ) {
  if ( in_array( $key, $rand_keys ) ) {
    echo '<h2 class="post-title">' . $post->post_title . '</h2>';
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question