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.

  • What should happen if there are multiple categories? – fuxia Nov 14 '12 at 23:45
  • there are a lot of categories but every single post belong to one and not to two or more – wpuser Nov 14 '12 at 23:47

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.


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

    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>';

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

<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!

  • Please add an explanation to your answer: why could that solve the problem? – fuxia Jul 23 '13 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.