Display random gallery images and its parent post title leading to parent post permalink

The solution to this is that you have to search for posts first, and afterwards to images to the post.

In my code I included a parameter exclude to ensure the current post is not delivered again.

Please keep in mind that if a post has no Image, none will be shown. Also, I did not include stylings or fallbacks, if there are no posts to show or something like that – but that should be no problem to work out.

Have fun!

$args = array(
    'post_type' => 'post',
    'numberposts' => 3,
    'post_status' => 'publish',
    'orderby' => 'rand',
    'exclude' => get_the_ID()
); 
$relatedposts = get_posts( $args );

echo '<ul>';

foreach ( $relatedposts as $related ) {

    $args = array(
        'post_type' => 'attachment',
        'numberposts' => 1,
        'post_parent' => $related->ID,
        'post_mime_type' => 'image',
        'orderby' => 'rand'
    ); 
    $attachments = get_posts($args);
    $thisimage = $attachments[0];

    echo '<li>';
        echo wp_get_attachment_image( $thisimage->ID, 'thumbnail' );
        echo '<a href="' . get_permalink( $related->ID ) . '">' . $related->post_title . '</a>';
    echo '</li>';

}

echo '</ul>';