WordPress related posts function
Monday 28th December 2009 by admin
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
-
-
global $constant_post_id;
-
$constant_post_id = $post->ID;
-
Use the wp_get_object_terms to get the post tags realting to the post in question
-
-
$tags = wp_get_object_terms($constant_post_id, ‘post_tag’);
-
Start a foreach statement based on each tag
-
-
foreach ($tags as $tag) :
-
$tag_content = $tag->slug;
-
// Show the tag name if you wish //
-
// Start an unordered list //
-
echo ‘<ul>’;
-
Get the tag ’slug’ as this is used in the following get_posts query
-
-
$tag_slug = $tag_content;
-
Now run a get_posts using the $tag_slug (above) and the post->ID which we decalred as a global in section 1
-
-
$relatedposts = get_posts(‘tag=’.$tag_slug.‘&exclude=’.$constant_post_id.”);
-
foreach(relatedposts as relatedposts) :
-
setup_postdata(relatedposts);
-
endforeach;
-
// end the unordered list – if you are using one //
-
echo ‘</ul>’;
-
endforeach;
-
And don’t forget to reset the query
-
-
wp_reset_query();
-
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:
-
-
function my_related_posts() {
-
global $constant_post_id;
-
$constant_post_id = $post->ID;
-
$tags = wp_get_object_terms($constant_post_id, ‘post_tag’);
-
foreach ($tags as $tag) :
-
$tag_content = $tag->slug;
-
// Show the tag name if you wish //
-
// Start an unordered list //
-
echo ‘<ul>’;
-
$tag_slug = $tag_content;
-
$relatedposts = get_posts(‘tag=’.$tag_slug.‘&exclude=’.$constant_post_id.”);
-
foreach(relatedposts as relatedposts) :
-
setup_postdata(relatedposts);
-
endforeach;
-
// end the unordered list – if you are using one //
-
echo ‘</ul>’;
-
endforeach;
-
}
-
So to use this function all you need to do is call my_related_posts();
Hope this helps
Popularity: 10% [?]



0
COMMENTS