Is it possible to display related posts from same category as the current post?
Leave a Reply
You must be logged in to post a comment.
Is it possible to display related posts from same category as the current post?
You must be logged in to post a comment.
One possibility:
Reference:
get_posts
wp_reset_postdata
wp_get_post_categories
Answer re-written based on
WP_Query()
:Here another clean and very flexible option:
Put this code in your functions.php file
Now you can simply call the function anywhere in your site using:
You may want to remove the list elements or style them as per your need.
*Edit – you to change this: post_not_in to this post__not_in in your query
you can use this code to get related posts from the same category
and use this code to get related posts from the same tags
This answer makes sure that related posts are ordered by how many tags match.
For example if an article has 3 tags and there is another article that has the exact same 3 tags it should appear at the top of the list.
Secondary sorting should be by post date so newer content is favored.
The inner query here is to select the content with the most matching tags, and then the outer query is just used to to apply secondary sorting by post date.
Note this query is written for SQL Server so some syntax may need updating (e.g. TOP vs LIMIT).