• Resolved MelmoSA

    (@melmosa)


    Hi Guys,

    I would really like to create a custom “Back Button” on the posts of my site and I’d like it to work by retrieving the url for the category/sub-category archive to which the post belongs.

    I’ve done a lot of searching and I’ve tried many things, but nothing has worked yet.

    is it possible?

    Thank you!

Viewing 5 replies - 1 through 5 (of 5 total)
  • First initial thought would be to use get_post_categories() – https://codex.www.ads-software.com/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.www.ads-software.com/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 =^.^=

    Thread Starter MelmoSA

    (@melmosa)

    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!

    Thread Starter MelmoSA

    (@melmosa)

    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 https://yoursite.com/category/term_name, the script would provide a link back to that page.

    If, however, they came from https://yoursite.com/ ( ie. not an archive page ) no link will be given; which is why I use the empty check in the above code.

    Thread Starter MelmoSA

    (@melmosa)

    It’s Perfect! Thank you so much!

    Can’t even tell you how many hours I spent on it.

    Much appreciated ??

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Custom Back Button’ is closed to new replies.