First initial thought would be to use get_post_categories() – https://codex.wordpress.org/Function_Reference/wp_get_post_categories
However, then it can be said “what if you have multiple categories?”
So let’s say you have a category tree like this and ALL categories are assigned to that post.
|- Cat 1
|- Sub-Cat 1
|- Cat 2
|- Sub-Cat 2
Sure you could do some magic to figure out which child category to use in your ‘Back To..’ link, but you’ll have to choose, and may send the user to the wrong sub-category archive.
If you want a true ‘Back to’ experience, use wp_get_referer() – https://codex.wordpress.org/Function_Reference/wp_get_referer
That way if they came from a sub-category page, wp_get_referer will provide the FULL url to that page. Short of it, I had some time, so here ya go: https://gist.github.com/JayWood/e7f2e83fb4d731abe7fa
I commented the heck outta the code so I hope it helps!
Happy Coding =^.^=
Thank you so much, really appreciate the effort 🙂
Unfortunately, it doesn’t seem to be working… But I’m pretty sure I’m using it wrong… I used it like this: Back text
If that was a ridiculous thing to do, I apologize… Still a little new to this…
Any further assistance would be greatly appreciated.
Thanks again!
Ok, it actually picked up on the link code 0.o
..sorry.
Correction:
Unfortunately, it doesn’t seem to be working… But I’m pretty sure I’m using it wrong… I used it like this: <a href=" I put the code here... "> Back </a>
Sorry, probably should have included a usage example:
<?php
$link = get_back_to_archive_link();
if ( ! empty( $link ) ) {
echo "<a href='$link'>My Link Text</a>";
}
If you read the comments, you’ll see that it will provide a link, only if a user is coming from a category or tag archive page.
So let’s say a user came from http://yoursite.com/category/term_name, the script would provide a link back to that page.
If, however, they came from http://yoursite.com/ ( ie. not an archive page ) no link will be given; which is why I use the empty check in the above code.
It’s Perfect! Thank you so much!
Can’t even tell you how many hours I spent on it.
Much appreciated 🙂