How to show below each post in WordPress 3 random posts?

  

4
Topic starter

I have WordPress site and below each article (post) I want to show 3 random articles (posts) so I can interlink all my posts. I want this to be simple code - only shown as a clickable text - nothing fancy...

Can you please help?

Maybe some code in functions.php?

Thanks

2 Answers
3

In your Child theme in functions.php add these lines of code:

/* Shortcode for random posts */
/* The shortcode to put in any post/widget is [my-random-posts] */
function my_rand_posts() {
 
    $args = array(
        'post_type'      => 'post',
        'orderby'        => 'rand',
        'posts_per_page' => 3,
    );
 
    $the_query = new WP_Query($args);
    $string = "";
    if ($the_query->have_posts()) {
        $string .= '<ul>';
        while ($the_query->have_posts()) {
            $the_query->the_post();
            $string .= '<li><a href="' . get_permalink() . '" target="_blank">' . get_the_title() . '</a></li>';
        }
        $string .= '</ul>';
        /* Restore original Post Data */
        wp_reset_postdata();
    } else {
        $string .= 'no posts found';
    }
 
    return $string;
}
 
add_shortcode('my-random-posts', 'my_rand_posts');
add_filter('widget_text', 'do_shortcode');

This code will create shortcode which you can put whenever you like! On line #8 (posts_per_page) you can choose how many posts will be shown - in our case: 3. 

The shortcode to put in any post/widget is: [my-random-posts]

Enjoy!

2

You can also create yout own WP plugin in order to keep the code and the shortcode in case you switch/change your WordPress theme.

Here is the code of my WordPress plugin showing the latest 3 posts (with the dates at the end 🙂 by using the shortcode: [my-plugin-recent-posts]:

<?php
 
/*
Plugin Name: My plugin recent posts shortcode
Plugin URI:  https://mypluginrecentpostsshortcode.com 
Description: WP plugin for showing recent posts with a shortcode
Author: My plugin recent posts shortcode Ltd.
Version: 1.0
Author URI:  https://mypluginrecentpostsshortcode.com 
Text Domain: my-plugin-recent-posts-shortcode
Domain Path: /languages/
 */
 
function my_plugin_recent_posts_shortcode() {
    $buffer = '<h4>Recent Posts:</h4><ul>';
 
    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 3,
    );
 
    $q = new WP_Query( $args );
 
    while ( $q->have_posts() ) {
        $q->the_post();
        $buffer .= '<li><a href=" ' . get_the_permalink() . '">' . get_the_title() . '</a> - ' . get_the_date() . ' </li>';
    }
    wp_reset_postdata();
 
    $buffer .= '</ul>';
 
    return $buffer;
}
 
add_shortcode( 'my-plugin-recent-posts', 'my_plugin_recent_posts_shortcode' );

...and this is the screenshot of my WordPress blog:

my wordpress plugin recent posts shortcode

Share: