# Displaying random posts on WordPress

> Show visitors a random post on your WordPress site using a plugin or a custom PHP shortcode to help them discover more content.

Source: https://helpcenter.ruachost.com/wordpress/guides/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?

- 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

1. **Log in to WordPress** with an administrator account.
2. In the dashboard, go to **Plugins → Add New**.
3. Search for **Random Post on Refresh**.
4. Click **Install Now**, then **Activate**.
5. Edit the page where you want random posts to appear.
6. 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.
7. Save the page.
8. Refresh the page → A random post will display each time.

## Method 2: Custom PHP Code (Advanced)

If you prefer not to use a plugin, you can add custom code to your theme:

1. Open your theme’s **functions.php** file.
2. 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();
       }
   }
   ```
3. Call the function in your template file where you want the random post to appear:

   ```
   <?php ruachost_random_post(); ?>
   ```

## 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.
