5

I want to ask on how to get the link of each category that have related post on it. I only got some code that will only display parent category. Any help would be much appreciated. Thanks!

<?php

$categories = get_categories();

foreach ($categories as $cat){
   if($cat->parent < 1){
      echo $cat->cat_name ;
   }
}

?>

1
  • wordpress.stackexchange.com
    – djechlin
    Feb 11, 2013 at 17:14

2 Answers 2

26

Sounds like you may want get_category_link - something like:

$categories = get_categories();
foreach ($categories as $cat) {
    $category_link = get_category_link($cat->cat_ID);
    echo '<a href="' . esc_url($category_link) . '" title="' . esc_attr($cat->name) . '">' . esc_html($cat->name) . '</a>';
}

should print out the links to the categories for you.

1
  • get_category_link uses get_term_link which applies the category_link filter for terms of type category. The filter has been deprecated since 2.5.0 (2008-03-29) and WP throws a warning for this. Anyone aware of a way to get a category link without a warning?
    – phip
    Apr 29, 2020 at 3:55
2

According to Function Reference/get category link

<?php get_category_link( $category_id ); ?> 

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.