Wordpress Snippets

Display Random Post From Specific Categories

Previously we have talked about displaying related posts and popular posts in WordPress but today, I have very interesting WordPress snippet for you. Recently, one of my client requested me to develop a section for his WordPress blog to feature an article on blog homepage but the catch was, the displayed article should be selected randomly from specific categories. It might sound scary at fist to display random post from multiple categories but for a WordPress developer like me, it was easy peasy. If I had to achieve this task in any other CMS then I might have to run SQL query to display random post from specific categories but WordPress made querying very easy for us. To make a specific request from database, we only have supply our arguments to WordPress functions.

A very common WordPress function to interact with database and fetch the posts on a page is WP_Query(). We can supply arguments to this function as an array to get the results we want. For this particular task, first I had to specify category IDs (or name, slug or combination of these) to get post from and while fetching post random in order also limit my results by one. So I created this custom query which display random post from specific categories.

You can use this following code snippet in any theme file or you can also create a new page template. Before using this code, don’t forget to replace category IDs that you want to fetch post from. You can also modify this query to get more than one random posts. One important thing to notice here that we are forcing WordPress to ignore sticky posts or this code will only display sticky post.

<?php

    // display random post from specific categories

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'cat' => '2, 6, 17, 38', // category IDs
        'orderby' => 'rand',
        'posts_per_page' => '1', // get 1 post only
        '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();

?>

Hire Us. Or just say Hi!
Need a job? Apply to get one.