Using WordPress ‘get_category_link()’ PHP function

The get_category_link() WordPress PHP function retrieves the URL for a given category.

Usage

get_category_link( $category );

Example:

Input:

$category_id = get_cat_ID('Travel');
$category_link = get_category_link($category_id);

Output:

https://example.com/category/travel/

Parameters

  • $category (int|object) – Required. The category ID or category object to get the link URL for.

More information

See WordPress Developer Resources: get_category_link()

Examples

Code:

$category_id = get_cat_ID('Travel');
$category_link = get_category_link($category_id);
echo '<a href="' . esc_url($category_link) . '" title="Travel">Travel</a>';

Explanation: This code gets the ‘Travel’ category ID, retrieves the corresponding URL, and outputs an HTML link.

Code:

$categories = get_categories();
foreach ($categories as $category) {
    $category_link = get_category_link($category->term_id);
    echo '<a href="' . esc_url($category_link) . '">' . esc_html($category->name) . '</a><br>';
}

Explanation: This code retrieves all categories and outputs a list of category links.

Code:

$args = array('parent' => 0);
$categories = get_categories($args);
foreach ($categories as $category) {
    $category_link = get_category_link($category->term_id);
    echo '<a href="' . esc_url($category_link) . '">' . esc_html($category->name) . '</a><br>';
}

Explanation: This code retrieves only top-level categories and outputs a list of their links.

Display a list of category links with post counts

Code:

$categories = get_categories();
foreach ($categories as $category) {
    $category_link = get_category_link($category->term_id);
    echo '<a href="' . esc_url($category_link) . '">' . esc_html($category->name) . ' (' . $category->count . ')</a><br>';
}

Explanation: This code retrieves all categories and outputs a list of category links with the number of posts in each category.

Code:

echo '<select onchange="window.location.href=this.value;">';
$categories = get_categories();
foreach ($categories as $category) {
    $category_link = get_category_link($category->term_id);
    echo '<option value="' . esc_url($category_link) . '">' . esc_html($category->name) . '</option>';
}
echo '</select>';

Explanation: This code retrieves all categories and outputs a dropdown menu with category links. When a category is selected, the browser navigates to the corresponding URL.