Display Link to Category in WordPress?

I am trying to figure out how to display the category of an article, and a link to the category. Any help would be greatly appreciated.

Related posts

Leave a Reply

4 comments

  1. If you want to do this on post page you can add something like the following to your single.php file of your theme.

    <div class="meta">Posted in: <span><?php the_category(', ') ?> </span></div>
    
  2. Note that: <?php the_category(', ') ?>will display the category as a link. which is good…. but if you want only the category URL (that is, the category link only), then you will have to use the <?php get_category_link($category_ID); ?> the $category_ID is required. once you fix that in, the category URL will be returned.

    Consider the example:

    <?php
        // Get the ID of a given category
        $category_id = get_cat_ID( 'Category Name' );
    
        // Get the URL of this category
        $category_link = get_category_link( $category_id );
    ?>
    
    <!-- Print a link to this category -->
    <a href="<?php echo esc_url( $category_link ); ?>" title="Category Name">Category Name</a>
    

    Now you can see how we got the category ID and then using it to get the category Link.
    Hope this answers your question well enough?

  3. You can use get_the_category()

    <?php
    $categories = get_the_category();
    $separator = ' ';
    $output = '';
    if($categories){
    foreach($categories as $category) {
        $output .= '<a href="'.get_category_link( $category ).'" title="'.esc_attr(sprintf( __( "View all posts in %s" ), $category->name ) ) .'">'.$category->cat_name.'</a>'.$separator;
    }
    echo trim($output, $separator);
    }
    ?>