Related Posts for Multiple Category Solution

On my WordPress post view page, I wish to show posts in the same category as the currently selected post.
My difficulty here was managing this to handle multiple categories, but also, a way to track which was the ‘category’ page that you viewed the page at.

For example, a standard route though the website would be Homepage > Category Page > Post, but for posts that sit in multiple categories, how do I know which category the user viewed before hitting the Post page, so that I can show related posts in that particular category.

I came up with a solution that made use of the wp_get_referer() method.
This returns the previous page URL.
With this, I have to handle if the page was visited from Google, and if the page was visited from another route in the website and make appropriate adjustments.

Functions

I created a function called referred_category to handle this.
Then I could simply call it from my post template file.
I passed into this function, the wp_get_referer() return value and the post ID for the current page.

The basic structure of this function is as follows:

Here is my actual function, with an included get_post_primary_category() function for deciding on the category id of the current post.

Now all I have to do is use that category ID in a loop on my post page and I can return the category posts as I wanted.

Flaw in my plan

Okay, in my get_post_primary_category() function, I request the category from the permalink to the current post.
What if that post is part of multiple categories? How do I decide which of the categories I’d like to show as ‘default’?

WordPress automatically decides upon the category to show in the permalink based upon the id numbers of the categories.
I found a plugin called Hikari Category Permalink which allows us to decide on which of my multiple post categories I’d like to use as the permalink.

It took some hours of research and some helpful plugins but I got the functionality I need complete!

Comments

comments

Powered by Facebook Comments