There is a little bug in this code (you can't add related post on a post with none related post).
You must put out the div "related-posts" of the brace.
if (!empty($related)) {
echo '<div id="related-posts">';
...
echo '</div>';
}
=>
echo '<div id="related-posts">';
if (!empty($related)) {
...
}
echo '</div>';