Wordpress Related Posts Shortcode


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function related_posts_shortcode( $atts ) {
  2.  
  3. extract(shortcode_atts(array(
  4. 'limit' => '5',
  5. ), $atts));
  6.  
  7. global $wpdb, $post, $table_prefix;
  8.  
  9. if ($post->ID) {
  10.  
  11. $retval = '
  12. <ul>';
  13.  
  14. // Get tags
  15. $tags = wp_get_post_tags($post->ID);
  16. $tagsarray = array();
  17. foreach ($tags as $tag) {
  18. $tagsarray[] = $tag->term_id;
  19. }
  20. $tagslist = implode(',', $tagsarray);
  21.  
  22. // Do the query
  23. $q = "
  24. SELECT p.*, count(tr.object_id) as count
  25. FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p
  26. WHERE tt.taxonomy ='post_tag'
  27. AND tt.term_taxonomy_id = tr.term_taxonomy_id
  28. AND tr.object_id = p.ID
  29. AND tt.term_id IN ($tagslist)
  30. AND p.ID != $post->ID
  31. AND p.post_status = 'publish'
  32. AND p.post_date_gmt < NOW()
  33. GROUP BY tr.object_id
  34. ORDER BY count DESC, p.post_date_gmt DESC
  35. LIMIT $limit;";
  36.  
  37. $related = $wpdb->get_results($q);
  38.  
  39. if ( $related ) {
  40. foreach($related as $r) {
  41. $retval .= '
  42. <li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>
  43. ';
  44. }
  45. } else {
  46. $retval .= '
  47. <li>No related posts found</li>
  48. ';
  49. }
  50. $retval .= '</ul>
  51. ';
  52. return $retval;
  53. }
  54. return;
  55. }
  56. add_shortcode('related_posts', 'related_posts_shortcode');

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.