Simple wordpress function to display random post link in anyplace or in widget without plugin, make random post shortcode easily, easy way to display random post.

How To Display Random Post

Using get_posts() function, we will make our random post function and display random post in anyplace, and using add_shortcode() function, we will make shortcode easily.

Random Post Function

Copy function code and paste it in your functions.php file, function code:

function WPTime_get_random_post(){
    $args = array(
        'orderby' => 'rand',
        'post_status' => 'publish',
        'posts_per_page' => 1, // count of random post
        'post_type' => 'post' // for multi post type, use: 'post_type' => array('post', 'page', 'your_custom_post_type')
    );

    $get_random_post = get_posts($args);

    foreach ( $get_random_post as $random_post ) {
        echo '<p><a href="'.get_permalink($random_post->ID).'">'.get_the_title($random_post->ID).'</a></p>';
    }

    wp_reset_postdata();
}

Count of post is “1”, you can change it ‘posts_per_page’ => 5, and for multi post type, use: ‘post_type’ => array(‘post’, ‘page’, ‘your_custom_post_type’) and you can remove “<p></p>” tag.

Display Random Post

Now go to anyplace, for example header.php file or footer.php file or anyplace, and use this code:

<?php WPTime_get_random_post(); ?>

Random Post Shortcode

Copy function code and paste it in your functions.php file, function code:

function WPTime_random_post_shortcode(){
    ob_start();
    WPTime_get_random_post();
    return ob_get_clean();
}
add_shortcode('random_post', 'WPTime_random_post_shortcode'); // use [random_post] shortcode.

Now use this shortcode [random_post] in your posts or in “Text” widget.

Shortcode In Text Widget

To display random post shortcode in “Text” widget, copy this line and paste it in your functions.php file, line:

add_filter('widget_text', 'do_shortcode'); // do shortcode in text widget.

Now go to “Text” widget, and in “Content” field, enter [random_post] shortcode.

wordpress random post in widget

For more information about shortcode in “Text” widget, read this tutorial.