Ezeewp – making wordress easy for you
contact us contact us contact us contact us contact us

"Developing WordPress themes, templates and WordPress plugins"

WordPress related posts function

Monday 28th December 2009 by admin

0

COMMENTS

Here is today’s addition to WordPress functions & tips – a quick way to add a simple related WordPress posts function without the need for a WordPress plugin.

This function works by linking the tags on a single page or single post page and can be used anywhere outside the loop e.g. the sidebar.

Firstly declare a global variable based on the post ID

  1.  
  2. global $constant_post_id;
  3. $constant_post_id = $post->ID;
  4.  

Use the wp_get_object_terms to get the post tags realting to the post in question

  1.  
  2. $tags = wp_get_object_terms($constant_post_id, ‘post_tag’);
  3.  

Start a foreach statement based on each tag

  1.  
  2. foreach ($tags as $tag) :
  3. $tag_content = $tag->slug;
  4. // Show the tag name if you wish //
  5. echo $tag->name;
  6. // Start an unordered list //
  7. echo ‘<ul>’;
  8.  

Get the tag ’slug’ as this is used in the following get_posts query

  1.  
  2. $tag_slug = $tag_content;
  3.  

Now run a get_posts using the $tag_slug (above) and the post->ID which we decalred as a global in section 1

  1.  
  2. $relatedposts = get_posts(‘tag=’.$tag_slug.‘&exclude=’.$constant_post_id.);
  3. foreach(relatedposts as relatedposts) :
  4. setup_postdata(relatedposts);
  5. echo ‘<li><a href="’.relatedposts->post_guide.‘">’.relatedposts->post_title.‘</a></li>’;
  6. endforeach;
  7. // end the unordered list – if you are using one //
  8. echo ‘</ul>’;
  9. endforeach;
  10.  

And don’t forget to reset the query

  1.  
  2. wp_reset_query();
  3.  

Voila a related posts query based on WordPress tags. All that is left is to make it a function ready to past into your functions.php file so you can simply use it anywhere you want here goes:

  1.  
  2. function my_related_posts() {
  3. global $constant_post_id;
  4. $constant_post_id = $post->ID;
  5. $tags = wp_get_object_terms($constant_post_id, ‘post_tag’);
  6. foreach ($tags as $tag) :
  7. $tag_content = $tag->slug;
  8. // Show the tag name if you wish //
  9. echo $tag->name;
  10. // Start an unordered list //
  11. echo ‘<ul>’;
  12. $tag_slug = $tag_content;
  13. $relatedposts = get_posts(‘tag=’.$tag_slug.‘&exclude=’.$constant_post_id.);
  14. foreach(relatedposts as relatedposts) :
  15. setup_postdata(relatedposts);
  16. echo ‘<li><a href="’.relatedposts->post_guide.‘">’.relatedposts->post_title.‘</a></li>’;
  17. endforeach;
  18. // end the unordered list – if you are using one //
  19. echo ‘</ul>’;
  20. endforeach;
  21. }
  22.  

So to use this function all you need to do is call my_related_posts();
Hope this helps

Popularity: 10% [?]

Please leave a response and trackback from your own site.

Leave a Reply