Link To Child Category For A Post

by Tnace   Last Updated October 09, 2019 17:08 PM

I'm trying to display a link to just the child category on a Wordpress post. For instance if the category for a post is parent > child I want to show a link to just the child category page.

I'm using code from here: Name of last category level for a post

It works perfectly but just prints the child category, how do I go about making it a link tot he child category?

 $allCat = get_the_category();
 $lastCat = array_reverse($allCat);
 echo $lastCat[0]->name;


Answers 1


You can use get_category_link() for that:

$allCat = get_the_category();
if( ! empty( $allCat ) ){
    $lastCat = array_reverse( $allCat );
    $last_cat_link = get_category_link( $lastCat[0] );
    if( ! is_wp_error( $last_cat_link ) ){
        echo '<a href="' . $last_cat_link . '">' . $lastCat[0]->name . '</a>';
    }
}

https://developer.wordpress.org/reference/functions/get_category_link/

freejack
freejack
October 09, 2019 16:42 PM

Related Questions


Updated March 07, 2018 05:08 AM

Updated February 24, 2017 12:08 PM

Updated June 21, 2017 14:08 PM

Updated June 29, 2015 18:03 PM

Updated March 20, 2019 23:08 PM