wordpress get the current category id name and slug

This gets and displays the current category id in a wordpress blog post if you have the current id, if not you can leave the $post_id blank and it should see if there is a category loaded to the current post if there is one.

This should return an array. 

Also i had to switch the the_ID(); for get_the_id(); or it just echos the post id in the middle of the page

PHP

$category_array = get_the_category( $post_id );
var_dump($category_array ); // this should show you an array of the category details

// get the primary category by grabbing the 1st bit of the array, not tested if the 1st part is actually the primary category. 
$category_id = $category_array[0]['term_id'];
$category_name = $category_array[0]['name'];
$category_slug = $category_array[0]['slug'];
// ^^ this actually gives the error -- Uncaught Error: Cannot use object of type WP_Term as array
// so we need to access the array using -> rather than brackets as its an object i think. 

// here is the working code:
$post_id = the_ID();
$category_array = get_the_category( $post_id );
$category_id = $category_array[0]->term_id;
$category_name = $category_array[0]->name;
$category_slug = $category_array[0]->slug;
var_dump($category_id);

echo "<pre>";
var_dump($category_array);
echo "</pre>";

Page Views

This page has been viewed 70 times.

Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹

Random Quote
Don't look to be the next Facebook, try to solve a real problem instead.
Unknown