<? php query_posts ('showposts = 5 & orderby = rand'); while (have_posts ()): the_post (); ?> <li> <a href=" the_permalink() ?>"title =" <? php the_title (); ?> "> <? Php the_title (); ?> </a> </ li> <? php endwhile; ?>

Replace “5” with your desired number to increase or decrease the number of random posts.

It is further customizable so that you can display posts from a specific category or tag.  Here is the code you need to add to the template of the page where you want to display the posts:  

<?php

    // display random posts from specific categories

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'cat' => '2, 6, 17, 38', // category IDs
        'orderby' => 'rand',
        'posts_per_page' => '5', // get 5 posts
        'ignore_sticky_posts' => 1,
    );

    $my_query = new WP_Query( $args );

    // the loop
    if ( $my_query->have_posts() ) :

        while ( $my_query->have_posts() ) : $my_query->the_post();

            // display article
            get_template_part( 'content', 'featured' );

        endwhile;

    endif;

    wp_reset_postdata();

?>

You can also display a certain number of randomly selected posts from each category on the category archives pages.

Let’s say you have two categories on your blog: Blogging and Marketing. You want to display 10 random posts from the category “Blogging” on the archives page of this category. Likewise, the archives page for the “Marketing” category will display a random selection of 10 posts.

This is how the code snippet would look: 

<? php if (is_category ()) {?> 
<? php $ hole_cat = get_the_category (); 
$ current_cat = $ hole_cat [0] -> cat_ID; 
query_posts (array ( 
'showposts' => 10,, 
category__and '=> array ($ 
current_cat ) ,, orderby' => rand, 
)); 
while (have_posts ()): the_post (); ?> 
<li> <a href=" the_permalink() ?>"title =" <? php the_title (); ?> "> <? Php the_title (); ?> </ a <> / li> 
<? php endwhile; ?> 
<? php}?>

Video: Display Random Posts

If you liked this post, please consider sharing it with your friends:


Source link

Leave a Reply

Your email address will not be published. Required fields are marked *