How to Create a Simple Related Posts Plugin

Your code looks ok at a brief scan of the code. What you need is a plugin header comment, some way to wrap it up and prepare it for output and a way to call it in your templates.

  1. Plugin comment: The minimum thing you need is /* Plugin Name: Your plugins Name */
  2. Wrap your plugin in a function and add it a filter

    add_filter( 'your-filter-name', 'pluginCallback' );
    function pluginCallback()
    {
        // Your code without any echo or direct HTML tag calls *)
    }
    
  3. Then add it to your template:

    echo apply_filters( 'your-filter-name', "" );
    

*) Instead of adding <div> HTML output directly, or echo DOM nodes (for e.g. echo '<div>';), simply put them into a string and return the result:

$html = "";
if ( $query->have_posts()  )
{
    while ( $query->have_posts() )
    {
        $query->the_post();

        $html .= '<div class="relatedthumb">';
        $html .= sprintf( '<a href="https://wordpress.stackexchange.com/questions/126970/%s" title="https://wordpress.stackexchange.com/questions/126970/%s">%s</a>',
            get_the_permalink(),
            get_the_title(),
            get_the_post_thumbnail( /* args */ )
        );
        $html .= '</div>';
    }
}
// ... etc.
return $html;