Generate Random Post Links Somewhere in the post

Edit

You have indicated that you wish to reuse this code, so it is better used within a function so that it can be called whenever you desire. I’ve made changes to my answer to reflect this below.


You can use the below code to generate a list of posts (in you case 2x random posts) together with a header. The output is formated in a way indicated by the image in your question. This code can be used anywhere within your theme –

my_post_list();

The function that does all of the work, below, should be placed in functions.php.

If you wish, you can pass a different list title to the function, as well as a different $args array. This allows you to customise the scope of your random Posts, targeting specific categories or tags, only searching a certain date range, or only looking for Posts where some custom data value is set for example – the possibilities are endless. Check out the Class Reference for WP_Query for more information on what you can do with these args.

/**
 * Output a list of posts under a heading
 *
 * @param string $title The title to output in the list heading
 * @param array $args   The arguments for getting the required posts
 */
function my_post_list($title="You may also like to read:", $args = array()){

    $defaults = array(  // Set some defaults for querying the Posts
        'ignore_sticky_posts'   => true,
        'posts_per_page'        => 2,
        'post_status'           => 'publish',
        'orderby'               => 'rand'
    );
    $args = wp_parse_args($args, $defaults);    // Parse any arguments passed to this function with the defaults to create a final '$args' array
    
    $random = new WP_Query($args);  // Query the Posts
    
    if($random->have_posts()) : // Check to make sure some random Posts were returned
    
        echo '<h4>' . $title . '</h4>';
        echo '<ul>';
        
        while($random->have_posts()) : $random->the_post(); // Create a new custom Loop, and for each Post set up the postdata
    
            printf('<li id="random-post-%1$s">', get_the_ID());
            
            printf(
                '<a href="%1$s" title="%2$s">%3$s</a>',
                get_permalink(get_the_ID()),
                the_title_attribute('before=Check out \'&after=\'&echo=0'),
                get_the_title()
            );
            
            echo '</li>';
            
        endwhile;
        wp_reset_postdata();    // Reset the postdata so that the rest of your Loop will work correctly
        
        echo '</ul>';
        
    endif;
    
}