Wordpress: get_the_category and echo out link to child-most/deepest category

二次信任 提交于 2019-12-06 00:33:22

Add this function in you're theme/functions.php file :

function get_deep_child_category( $categories )
{
    $maxId = 0;
    $maxKey = 0;
    foreach ( $categories as $key => $value )
    {
        if ( $value->parent > $maxId )
        {
            $maxId = $value->term_id;
            $maxKey = $key;
        }
    }
    return $categories[$maxKey];
}

Then let's say as in you're example in theme/search.php you do

$categories = get_the_category();
if ( $categories ) :
    $deepChild = get_deep_child_category( $categories );
    ?>
        <a href="<?php echo get_category_link( $deepChild->term_id ); ?>" title="<?php echo sprintf( __( "View all posts in %s" ), $deepChild->name ); ?>"><?php echo $deepChild->name; ?></a>
    <?php 
endif;

From my knoledge there is no other way of sorting categories thru get_the_category() but i might be mistaken and the code above wouldn't be the best way of doing things if so .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!