While working on a client project, there was a requirement, where we had to include the name of the category and the category link in the post excerpt as well as the post itself. It’s a simple enough solution. And here’s what you need to do.
If you already know the Category Name..
To fetch the category link, you’ll have to first fetch the category ID. You can do this with the help of get_cat_ID function() function.
$category_id = get_cat_ID( ‘Category Name’ );
Here you can get the ID of any category by specifying the name of the category, in place of ‘Category Name’. This ID is then saved inside a variable called $category_id.
$category_link = get_category_link( $category_id );
We then pass this $category_id as a parameter in the function called get_category_link() and store the result in $category_link. Here we are basically storing the link inside a variable so as to display it later using the HTML code.
<?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 );
?>
<a href=”<?php echo esc_url( $category_link ); ?>” title=”Category Name”>Category Name</a>
The drawback of this method is that you need to specify the category name inside the function. If you want to fetch the category name itself then you need a slightly different approach here.
Fetching the post Category
To fetch the post category, you need to use something called as get_the_category() function.
$the_cat = get_the_category();
This function returns the current post category if you use it inside a loop. However if you want to use it outside of the loop then you’ll need to pass the post ID as a parameter.
$the_cat = get_the_category( $id );
Once we fetch the categories, we will fetch the category name of the first category in the array.
$category_name = $the_cat[0]->cat_name;
After getting the category name, we simply use the previous code and replace ‘Category Name’ with the variable $category_name.
$category_id = get_cat_ID( $category_name );
$category_link = get_category_link( $category_id );
Or we can write these two lines in one single line as follows –
$category_link = get_category_link( $the_cat[0]->cat_ID );
The final code to fetch category name and category link
<?php
$the_cat = get_the_category();
$category_name = $the_cat[0]->cat_name;
$category_link = get_category_link( $the_cat[0]->cat_ID );
?>
<a href=”<?php echo $category_link ?>”
title=”<?php echo $category_name ?>” >
<?php echo $category_name ?>
</a>
Place this code inside content.php or single.php or if you want to use it outside of the loop then simply make a small adjustment and add post_id as a parameter inside get_the_category() function and you’re good to go!
Leave a Reply