RPeraltaJr
7/15/2017 - 7:02 AM

Get a specific post's categories

Get a specific post's categories

<?php
  $post_id = get_the_ID(); // gets the post's ID
  $post_categories = wp_get_post_categories( $post_id ); // gets the post's ID
  $cats = array(); // create an array

  $len = count($post_categories); // how many categories does this post have?
  $i = 0; // start count at 0
  foreach($post_categories as $c){
    $cat = get_category( $c );
    $cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug ); // insert category into new array
    echo $cat->name;
    if($i !== $len - 1) {
			echo ", "; // add a comma
		}
		$i++;
  }
?>