Displaying random post on WordPress
Adding random posts to your WordPress site is a great way to keep visitors engaged and encourage them to explore more content. On ruachost.com, you can achieve this using a plugin or by adding a shortcode.
Why Display Random Posts?
Section titled “Why Display Random Posts?”- Keeps your site fresh by showing different content on each visit.
- Increases page views by encouraging users to discover older posts.
- Enhances user engagement with dynamic content.
Method 1: Using the Random Post on Refresh Plugin
Section titled “Method 1: Using the Random Post on Refresh Plugin”-
Log in to WordPress with an administrator account.
-
In the dashboard, go to Plugins → Add New.
-
Search for Random Post on Refresh.
-
Click Install Now, then Activate.
-
Edit the page where you want random posts to appear.
-
Add the shortcode:
php
[random_post_on_refresh]- Optionally, specify post IDs to randomize only certain posts:
php
[random_post_on_refresh ids="37,50,30"]Replace the numbers with your actual post IDs.
-
Save the page.
-
Refresh the page → A random post will display each time.
Method 2: Custom PHP Code (Advanced)
Section titled “Method 2: Custom PHP Code (Advanced)”If you prefer not to use a plugin, you can add custom code to your theme:
-
Open your theme’s functions.php file.
-
Add the following snippet:
function ruachost_random_post() {$args = array('orderby' => 'rand','posts_per_page' => 1);$random_post = new WP_Query($args);if ($random_post->have_posts()) {while ($random_post->have_posts()) {$random_post->the_post();echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';}wp_reset_postdata();}} -
Call the function in your template file where you want the random post to appear:
<?php ruachost_random_post(); ?>
Important Notes
Section titled “Important Notes”- The plugin requires posts to have a featured image to avoid errors.
- Always back up your theme before editing
functions.php. - Use a child theme to preserve changes during updates.