get_category_link( int|object $category )

Retrieves category link URL.


Description Description

See also See also


Top ↑

Parameters Parameters

$category

(int|object) (Required) Category ID or object.


Top ↑

Return Return

(string) Link on success, empty string if category does not exist.


Top ↑

More Information More Information

This function returns the correct url for a given Category ID. In a Plugin or Theme, it can be used as early as the setup_theme Action. Any earlier usage, including plugins_loaded, generates a Fatal Error.


Top ↑

Source Source

File: wp-includes/category-template.php

function get_category_link( $category ) {
	if ( ! is_object( $category ) ) {
		$category = (int) $category;
	}

	$category = get_term_link( $category );

	if ( is_wp_error( $category ) ) {
		return '';
	}

	return $category;
}


Top ↑

Changelog Changelog

Changelog
Version Description
1.0.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Codex

    Category Link

    <?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>
    
    
  2. Skip to note 2 content
    Contributed by rdmi

    Worth remembering that a category_id is a term_id and not a term_taxonomy_id

    (And, yes, you can figure that out from reading the code. But these sometimes will be the same, fooling some people into thinking that the term_taxonomy_id was right. But sooner or later you will probably get examples where they are different, and then things do not work right.)

  3. Skip to note 3 content
    Contributed by sammuelhg

    Example of a categories list with the Bootstrap 5 card and badge count.

    <div class="card border border-0 m-2" style="width: 250px;">
    
        <div class="card-header bg-primary text-white">
            <h5>Categorias</h5>
        </div>
    
        <?php
        foreach ( $categories as $category ) {
            echo '<a class="text-decoration-none list-group-item list-group-item-action text-dark" href="' . esc_attr( esc_url( get_category_link( $category->term_id ) ) ) . '">;
            echo '<div class="d-flex justify-content-between align-items-start">';
            echo esc_html( $category->name );
            echo '<span class="badge bg-primary rounded-pill">' . esc_html( $category->count ) . '</span>';
            echo '</div>';
            echo '</a>';
        }
        ?>
    
    </div>

You must log in before being able to contribute a note or feedback.