Yogesh Chauhan's Blog

How to get category name using post id in WordPress?

in WordPress on 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.

Syntax


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().

Example


$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');

var_dump($categories);

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


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to Use ROLLUP Operator in SQL and MySQL?SQL/MySQLList of social media icon logo color codes in HEXMiscellaneousSlider animation using CSS transform propertyCSSHow to reference an aliased column in the WHERE clause?SQL/MySQLHow to use [] (square brackets) function in Envision Basic?Envision BasicHow to add a Pie Chart in Angular App?AngularHow to check if the page is single post page in WordPress?WordPressLIKE and ILIKE Operators in PostgresPostgresHow to define variables in SCSS (Sass)?SCSSDROP DATABASE (remove a database) from PostgresPostgresHow to link/add CSS file to HTML Document?CSSHow to insert Bootstrap 4 in Angular 9 app?Angular