How to get category name using post id in WordPress?
February 7, 2021

We can use inbuilt WordPress function get_the_category() to do that.

get_the_category() used to retrieve post category or categories.


get_the_category( int $post_id = false )

where $post_id is optional. The defaults value is false but it defaults to current post ID.

It returns an array of objects, one for each category assigned to the post.

👉 This function only returns results from the default “category” taxonomy and not from custom taxonomies. To get results of custom taxonomies we can use get_the_terms().


$categories = get_the_category('1');//$post->ID

foreach($categories as $category){
  echo $category->name;

More get_the_category() Examples

Show the First Category Name Only

$categories = get_the_category();
if ( ! empty( $categories ) ) {
    echo esc_html( $categories[0]->name );   

Dump all the categories related to a post

$categories = get_the_category('1');


Get the Post Categories From Outside the Loop

$post = get_post();
if ( $post ) {
    $categories = get_the_category( $post->ID );
    var_dump( $categories );

Read more on: WordPress


Leave a Reply

Most Read

#1 How to set opacity or transparency using CSS? #2 Pagination in CSS with multiple examples #3 How to check if radio button is checked or not using JavaScript? #4 How to make HTML form interactive and using CSS? #5 How to uninstall Cocoapods from the Mac OS? #6 How to add Read More Read Less Button using JavaScript?

Recently Posted

Feb 24 How to modify the latest post array using get_posts() in WordPress? Feb 22 WordPress: How to get ACF field values from another post? Feb 22 WordPress: How to print ACF repeater field values? Feb 22 WordPress: How to print ACF array field values? Feb 21 WordPress: How to get field values in Advanced Custom Fields? Feb 21 WordPress: How to add a Search Icon in Menus with toggle effect using jQuery?

You might also like these

How to Display Related Posts in WordPress?WordPressWhat does it mean by Continuous Integration, Continuous Delivery and Continuous Deployment?MiscHow to modify the latest post array using get_posts() in WordPress?WordPressSteps to Secure a VPNMiscHow to check if the page is the home page in WordPress?WordPressAggregate Functions Examples in Postgres for BeginnersPostgresThe Lending Club Analysis using Logistic Regression and Random Forest in RStudioMiscStyling Lists with CSSCSSHow to check if radio button is checked or not using JavaScript?JavaScriptAn Example of Cross-site Scripting (XSS) Attack in PHP and How to Avoid It?PHPLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQLWhat is Hoisting in JavaScript?JavaScript