title: WordPress shortcode to display related posts
body: <p>WordPress shortcode to display related posts</p>
  
  <p>How To Display Related Posts in WordPress Manually </p>
  
  <p>This is my code:</p>
  
  <pre><code>function related_posts_shortcode( $atts ) {
  extract(shortcode_atts(array(
      'limit' =&gt; '5',
  ), $atts));
  
  global $wpdb, $post, $table_prefix;
  
  if ($post-&gt;ID) {
      $retval = '&lt;ul&gt;';
      // Get tags
      $tags = wp_get_post_tags($post-&gt;ID);
      $tagsarray = array();
      foreach ($tags as $tag) {
          $tagsarray[] = $tag-&gt;term_id;
      }
      $tagslist = implode(',', $tagsarray);
  
      // Do the query
      $q = "SELECT p.*, count(tr.object_id) as count
          FROM $wpdb-&gt;term_taxonomy AS tt, $wpdb-&gt;term_relationships AS tr, $wpdb-&gt;posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id  = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post-&gt;ID
              AND p.post_status = 'publish'
              AND p.post_date_gmt &lt; NOW()
          GROUP BY tr.object_id
          ORDER BY count DESC, p.post_date_gmt DESC
          LIMIT $limit;";
  
      $related = $wpdb-&gt;get_results($q);
      if ( $related ) {
          foreach($related as $r) {
              $retval .= '
  &lt;li&gt;&lt;a title="'.wptexturize($r-&gt;post_title).'" href="'.get_permalink($r-&gt;ID).'"&gt;'.wptexturize($r-&gt;post_title).'&lt;/a&gt;&lt;/li&gt;';  
     }
      } else {
          $retval .= '&lt;li&gt;No related posts found&lt;/li&gt;';
      }
      $retval .= '&lt;/ul&gt;
    ';
      return $retval;
      }
      return;
   }
   add_shortcode('related_posts', 'related_posts_shortcode');
  </code></pre>
  
  <p>It does not work as I would like. What I am doing wrong?</p>
  
  <p>Any help is appreciated.</p>