Back button to parent category (from Post/product template to archive template)

Hey everyone,

Is there a way that i can make a back button on a post/product template page that will go back to the parent categorie archive template?

So (in my case using woocommerce) for example: user is on /all categories/catgegory A/productpage
and back button will only be on product pages going to previous parent category.

On the old site i used a “cheap” script that basically went back to whatever the browser was on, but that was a very bad solution and has other problems (like when they come straight to product page or put something in shopping cart).

I am seeing issues with a new Woocommerce site that isn’t done yet, but had to go live already. I am gathering info from heatmaps/user paths/etc… and notice that the breadcrumbs aren’t popular for going back to the parent category. Of course i can do other things in styling, but a short button (especially for smaller screens) would be more convenient.

If someone only has an idea or link, that is of course also welcome. I found a tiny bit of info and methods, but i could not get anything to work.

Hey Stan,

do your products always have exactly one category (no more, no less) attached to them?

Best,

André

@aslotta 80% has only one category, but the other 20% often have 2 categories and in rare cases 3.
Hmm, that is of course a really good point!

Hey Stan,

maybe you just wanna output the categories somewhere in the template as links to their archive pages. That way it does not matter how many categories a product has. Probably the better option. :slight_smile:

Best,

André

Yes i agree. Although i do have that already, but there is room for improvement.
In other words, best way is to improve the website style a bit :wink:
example on product page (still work in progress)

Oh and to convince my cliënt again “this is the way” :face_with_peeking_eye:

Hey Stan,

although I don’t think it’s the best approach I just wanted to show you one way of approaching it using a small function to fetch the product category archive url and outputting a button only if there is exactly one category attached to the product: Video uploaded to CleanShot Cloud.

This is the function from the video:

function get_product_category_archive_link() {
    global $post;
    $cats = get_the_terms( $post->ID, 'product_cat' );
    if ( is_array( $cats ) && count( $cats ) === 1 ) {
        $cat = reset( $cats );
        return get_term_link( $cat );
    }

    return false;
}

Hope this helps.

Best,

André

1 Like

@aslotta Thanks André for the whole explanation and code (i saved the video).

I just tried it on cloned demo site and it worked (also having wpcodebox ready to go). I do actually have some other websites with a whole different setup that could benefit from this.