I like to share code to retrieves post categories. Most of the time, while creating a custom theme as per the client’s needs. We have to find a post category. This code would help you to find the exact post categories.
In WordPress To get category name we use get_the_category() function. It finds the list of post categories.
If you would like to read more about this function then you must check inside your wp-includes folder.
Path for this function:
wp-includes\category-template.php line number 77
Note: This function only returns results from the default “category” taxonomy.
<?php $cat = get_the_category(); ?>
$cat would contain array of WP_Term objects.
To find WordPress Post First Category
<?php echo $cat->cat_name; ?> // first category <?php echo $cat->cat_name; ?> // Second
Here zero(0) is the index of WP-Term objects. If you want you can fetch like wise from 0 to 1 , 2 ,3 so on.
Or you can iterate the entire object to list all.
WordPress Get Category By Id
A function is available that displays the category name by the category ID.
<?php echo get_the_category_by_ID( $cat_ID ); ?>
The above function is used to Retrieves category names based on category ID.
We have to pass Category ID. It will return Category name on success or WP_Error on failure.
Get category list either HTML list or custom format.
<?php echo get_the_category_list(); ?>
It will return the list in ul li format by default. If we provide a comma as a separator and the post has more than one category. It would use a comma to separate them.
Check if post has specific category
Use this function to find if post follows specifc category or not.
<?php if(in_category('Project')): ?> <p><?php the_title(); ?></p> <?php endif; ?>
Here is another post that would help you to detect https in PHP.