How to Get Post Category Name and URL in WordPress

Display the categories in the post details page in WordPress. get_the_category() returns the categories data (name, slug, url, etc) of the current post. Based on this category data you can display the category links in post details page. The following code helps to display the current post categories with the link.

$categories get_the_category();
$separator ' ';
$output '';
if ( ! empty( 
$categories ) ) {
    foreach( 
$categories as $category ) {
        
$output .= '<a href="' esc_urlget_category_link$category->term_id ) ) . '" alt="' esc_attrsprintf__'View all posts in %s''textdomain' ), $category->name ) ) . '">' esc_html$category->name ) . '</a>' $separator;
    }
    echo 
trim$output$separator );
}

Leave a reply

keyboard_double_arrow_up