How To Add Random Post Widget with Thumbnail in WordPress

Estimated reading time: 4 min

Add Random Post with Thumbnail Widget in WordPress (Code Included). Enhance your WordPress sidebar with a custom widget that displays a random post and its thumbnail.


How to Add a Random Post Widget with Thumbnail in WordPress

Want to spice up your sidebar with dynamic content? A great way to do this is by adding a Random Post Widget that displays a random article along with its thumbnail. This is perfect for keeping your site fresh and engaging on every page load.


Add Random Post Widget with Thumbnail in WordPress

Here’s a step-by-step look at how the custom widget works:

1. The Widget Setup

We define a new class RandomPostWidget that extends the core WP_Widget class. Inside the constructor, we register the widget with a title and description, which WordPress uses in the admin area.

2. Widget Settings

The form() method adds a simple input field so users can enter a custom title for the widget in the backend. The update() method makes sure the data is sanitized before saving.

3. Displaying the Widget

The magic happens in the widget() method. We query WordPress for one random post using WP_Query, check for a featured image with has_post_thumbnail(), and display the image and title linked to the post. If no post is found, a fallback message is shown.

4. Register the Widget

Finally, we use register_widget() inside a function hooked to widgets_init. This makes the widget available in the Appearance → Widgets section of the admin dashboard.

You can copy and paste the full code into your theme’s functions.php or a custom plugin. It’s lightweight, effective, and totally customizable.

This widget uses WP_Query to pull a random post and then shows its thumbnail and title as a link. It’s fully customizable and can be added directly to your functions.php file or a custom plugin.

The Full Code

class RandomPostWidget extends WP_Widget
{
    function __construct()
    {
        parent::__construct(
            'RandomPostWidget',
            __('Random Post and Thumbnail', 'text_domain'),
            array('description' => __('Displays a random post with thumbnail', 'text_domain'))
        );
    }

    function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : '';
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>">Title:</label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text"
                   value="<?php echo esc_attr($title); ?>">
        </p>
        <?php
    }

    function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        return $instance;
    }

    function widget($args, $instance)
    {
        echo $args['before_widget'];

        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }

        $random_post = new WP_Query(array(
            'posts_per_page' => 1,
            'orderby' => 'rand',
            'post_status' => 'publish'
        ));

        if ($random_post->have_posts()) {
            while ($random_post->have_posts()) {
                $random_post->the_post();
                ?>
                <div class="random-post-widget">
                    <a href="<?php the_permalink(); ?>">
                        <?php if (has_post_thumbnail()) the_post_thumbnail('thumbnail'); ?>
                        <p><?php the_title(); ?></p>
                    </a>
                </div>
                <?php
            }
            wp_reset_postdata();
        } else {
            echo '<p>No posts found.</p>';
        }

        echo $args['after_widget'];
    }
}

function register_random_post_widget()
{
    register_widget('RandomPostWidget');
}
add_action('widgets_init', 'register_random_post_widget');

Just paste this code into your theme’s functions.php file or a custom plugin file. You’ll now have a new widget called “Random Post and Thumbnail” in your widget area.


🏷️ Tags: wordpress widget, display random post, wordpress development, sidebar widget, post thumbnail, wp_query, custom widget, php code, functions.php, wordpress plugins


Discover more from HelpZone

Subscribe to get the latest posts sent to your email.

Want to support us? Let friends in on the secret and share your favorite post!

Photo of author

Flo

How To Add Random Post Widget with Thumbnail in WordPress

Published

Welcome to HelpZone.blog, your go-to hub for expert insights, practical tips, and in-depth guides across technology, lifestyle, business, entertainment, and more! Our team of passionate writers and industry experts is dedicated to bringing you the latest trends, how-to tutorials, and valuable advice to enhance your daily life. Whether you're exploring WordPress tricks, gaming insights, travel hacks, or investment strategies, HelpZone is here to empower you with knowledge. Stay informed, stay inspired because learning never stops! 🚀

👍 Like us on Facebook!

Closing in 10 seconds

Leave a Reply