Single.php back button to parent category

I want to add a back button that goes to the parent category of the actual single post that the user is viewing. How can I do that?

<h2 class="link"><a href="#">Return</a></h2>

Thank you.

Related posts

Leave a Reply

3 comments

  1. You can use get_the_category() and return the first result as in the example. Technically you could have several parent categories so you need to deal with this separately or expect that the first element of the array is always the right parent category.

  2. Paste this code in single.php according to your theme style

    $cats=get_the_category();
        foreach($cats as $cat){
    /*check for category having parent or not except category id=1 which is wordpress default category (Uncategorized)*/
            if($cat->category_parent == 0 && $cat->term_id != 1){
                echo '<h2 class="link"><a href="'.get_category_link($cat->term_id ).'">Return</a></h2>';
            }
            break;
        }
    

    Output HTML form this code:

    <h2 class="link"><a href="(Link to first category which not have any parent category)">Return</a></h2>
    

    Important Link:
    get_the_category

  3. <h2 class="link"><a href="<?php $cat = get_the_category(); $cat = $cat[0]; echo get_category_link($cat->cat_ID); ?>">Return</a></h2>
    

    This should work!