Find Related Posts Under Same Category/Tags

Nowadays very oftenly it is required to display related posts (or other post types) underneath your content. This engage readers, and provide them link to related posts to read, and effectively make them spend more time on website. Also, related posts come with added SEO benefits, as they provide internal links to your content. So, how you should go about displaying related posts in website?

To work with, you will need some sample content. So, let’s create a few posts and assign them on a few categories.

Implementation Steps:

1. In step one you have to retrieve the terms assigned to current post for which you will retrieve posts from blog. For, this we can use this snippet.

In this, we used a predefined function of wordpress "wp_get_post_terms()" for details of this function please refer to codex link.


2.

After retrieving terms assigned to current post you have to retrieve the related posts using "WP_Query". Code will be look a like as follows:

After, this we will get list of posts in (Object Array), which should be used with while loop for displaying content retrieved in list.

3.

This is the last step in showing related posts. The result you get in step, put it in while loop to show final results.


Finally, after combining all the steps you will get the following code.


No comments:

Post a Comment