Q:

How to get Category name by id post in wordpress

I want to make an api in wordpress, then I have a create a code like this :

case 'product_onsale':
 $response = array();
 $args = array(
  'post_type' => 'product',
  'posts_per_page' => 30,
  'meta_query' => array(
   'relation' => 'OR',
   array( // Simple products type
    'key' => '_sale_price',
    'value' => 0,
    'compare' => '>',
    'type' => 'numeric'
   ) ,
   array( // Variable products type
    'key' => '_min_variation_sale_price',
    'value' => 0,
    'compare' => '>',
    'type' => 'numeric'
   )
  )
 );
 $loop = new WP_Query($args);
 if ($loop->have_posts()):
  $meta = array(
   "api_status" => 1,
   "api_message" => "success",
   "result" => ""
  );
  $meta = array();
  while ($loop->have_posts()):
   $loop->the_post();
   $meta['result'][] = array(
    "id" => get_the_ID() ,
    "post_name" => get_the_title() ,
    "stock_status" => get_post_meta(get_the_ID() , '_stock_status', true) ,
    "price" => get_post_meta(get_the_ID() , '_price', true) ,
    "regular_price" => get_post_meta(get_the_ID() , '_regular_price', true) ,
    "sale_price" => get_post_meta(get_the_ID() , '_sale_price', true) ,
    "Stock_status" => get_post_meta(get_the_ID() , '_stock_status', true) ,
    "category" => the_category() ,
   endwhile;
  endif;
  echo json_encode($meta);
  break;

then in there, I want to show the category by post id in my result, I've try add 

the_category

what I need to improve in my code so it's can be work like what I want ?

A:

Inside the while loop you can get the categories of that post by get_the_category()
$CatObj = get_the_category();
This will provide you with array of categories in variable $CatObj.
Run a simple foreach loop to get all the categories in an array $catnames.
$catnames = array();
        foreach ($CatObj as $key => $value) {
            $catnames[] = $value->name;
        }

Now by using implode function of php , display comma separated categories inside the while loop , as below :
echo implode(', ', $catnames);

