hesam hesam - 4 months ago 12
JSON Question

Show WP category id in json

I made a page that shows some data in json format from a Wordpress database. Now I want show the category id of posts, but it shows all the ids before the object

"ads"


enter image description here

My source:

<?php

header("Content-type: application/json");

include ('wp-load.php');


$loop = new WP_Query(array( 'post_status' => 'publish', 'post_type' => 'post'));
if($loop->have_posts()) : while($loop->have_posts()) : $loop->the_post();
$posts[] = array(
'id' => $post->ID,
'post_title' => $post->post_title,
'post_content' => $post->post_content,
'guid' => $post->guid,

'thumbnail' => (has_post_thumbnail() ? get_the_post_thumbnail_url() : ''),
'cats' => the_category_ID(),

);
endwhile; endif;
echo json_encode(array('ads' => $posts));

?>

Answer

It shows IDs before because of this line 'cats' => the_category_ID(),

What does this function do?

This function actually echos the category ID ( as it's argument is true by default ).

How to fix?

Pass false inside the_category_ID like this the_category_ID( false )

Corrected code

header("Content-type: application/json");

include ('wp-load.php');


$loop = new WP_Query(array( 'post_status' => 'publish', 'post_type' => 'post'));
if($loop->have_posts()) : while($loop->have_posts()) : $loop->the_post();
    $posts[] = array(
        'id' => $post->ID,
        'post_title' => $post->post_title,
        'post_content' => $post->post_content,
        'guid' => $post->guid,

        'thumbnail' => (has_post_thumbnail() ? get_the_post_thumbnail_url() : ''),
        'cats' => the_category_ID( false ),

    );
endwhile; endif;
echo json_encode(array('ads' => $posts));