How to get the category id and link in wordpress post page

How to get the category id and link in wordpress post page or within the loop.

In wordpress you can use their default functions to get the category or taxonomy id or link. Below is the code for getting the category id or link Outside of single.php or post loop.

<?php

$terms = get_the_terms( $post->ID, ‘category’);

echo “<pre>”;
print_r($terms);
echo “</pre>”;

$cat_link = get_category_link( $terms[0]->term_id );

echo $cat_link;

?>

Here is the code if you are getting the category inside the single.php or post loop

<?php
$cats = get_the_category();

echo “<pre>”;
print_r($cats);
echo “</pre>”;

$cat_link = get_category_link( $cats[0]->term_id );

echo $cat_link;

?>

Please watch the video to understand more.

 

 

Leave a Comment