PHP Learner PHP Learner - 29 days ago 7
JSON Question

get all posts from desired category in json format?

<?php

include("../wp-config.php");
// set header for json mime type
header('Content-type: application/json;');
$cat_id=array(12,13,14);
$post=array('category__in' => $cat_id,'posts_per_page=-1');

$category_query = new WP_Query($post);

// print_r($category_query);
while ($category_query->have_posts())
{

$jsonpost=$category_query->the_post();
$id=$post->ID;
$post_title=get_the_title();
$image=wp_get_attachment_url(get_post_thumbnail_id($id, 'thumbnail'));
$content=strip_tags(apply_filters('the_content',$post->post_content));
/* echo $content;
echo $image;*/
$jsonpost=array('post_title'=>$post_title,'post_content' =>$content,'post_image' => $image);

/*======== PRODUCT COLLECTION OUTPUT AS JSON FORMAT ======*/

$output['post_details'] = $jsonpost;
echo (json_encode($output,JSON_UNESCAPED_SLASHES));
}
//print_r($jsonpost);exit();

$post1=array('cat'=> 12,'order' => 'DESC');
$category_query1 = new WP_Query($post1);
while ($category_query1->have_posts())
{

$jsonpost1=$category_query1->the_post();
$id=$post->ID;
$post_title=get_the_title();
$image=wp_get_attachment_url(get_post_thumbnail_id($id, 'thumbnail'));
$content=strip_tags(apply_filters('the_content',$post->post_content));
$jsonpost1=array('post_title'=>$post_title,'post_content'=>$content,'post_image'=>$image);
$output1['Latest_news'] = $jsonpost1;
/*======== PRODUCT COLLECTION OUTPUT AS JSON FORMAT ======*/

// print_r($output);
echo (json_encode($output1,JSON_UNESCAPED_SLASHES));
}
//wp_reset_postdata();

?>


I'm getting the result as below:

{"post_details":
{"post_title":"Breaking-News2","post_content":"Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/1022201314344PM_635_nokia-Lumia-1520.jpeg"}
}
{"post_details":
{"post_title":"breaking news1","post_content":"Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia,\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/breaking_news.jpg"}
}
{"post_details":
{"post_title":"standard stories","post_content":"Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia,\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/index.jpg"}
}
{"post_details":
{"post_title":"breaking-news","post_content":"The first line of Lorem Ipsum, &#8220;Lorem ipsum dolor sit amet..&#8221;, comes from a line in section 1.10.32.\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/breakingNews.jpg"}
}
{"post_details":
{"post_title":"call-out","post_content":"Lorem Ipsum has been the industry&#8217;s standard dummy tex\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/callout.jpg"}
}
{"Latest_news":
{"post_title":"Breaking-News2","post_content":"Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/1022201314344PM_635_nokia-Lumia-1520.jpeg"}
}
{"Latest_news":
{"post_title":"breaking news1","post_content":"Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia,\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/breaking_news.jpg"}
}
{"Latest_news":
{"post_title":"breaking-news","post_content":"The first line of Lorem Ipsum, &#8220;Lorem ipsum dolor sit amet..&#8221;, comes from a line in section 1.10.32.\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/breakingNews.jpg"}
}


But I want to display my response in the following way:

{
"post_details":
[
{
"post_title": "Breaking-News2",
"post_content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ",
"post_image": "http://localhost/police/wp-content/uploads/2014/09/1022201314344PM_635_nokia-Lumia-1520.jpeg"
},
{
"post_title": "breaking news1",
"post_content": "Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, ",
"post_image": "http://localhost/police/wp-content/uploads/2014/09/breaking_news.jpg"
},
{
"post_title": "standard stories",
"post_content": "Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, ",
"post_image": "http://localhost/police/wp-content/uploads/2014/09/index.jpg"
},
{
"post_title": "breaking-news",
"post_content": "The first line of Lorem Ipsum, “Lorem ipsum dolor sit amet..”, comes from a line in section 1.10.32. ",
"post_image": "http://localhost/police/wp-content/uploads/2014/09/breakingNews.jpg"
},
{
"post_title": "call-out",
"post_content": "Lorem Ipsum has been the industry’s standard dummy tex ",
"post_image": "http://localhost/police/wp-content/uploads/2014/09/callout.jpg"
}
],
"Latest_posts":
[
{
"post_title": "Breaking-News2",
"post_content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ",
"post_image": "http://localhost/police/wp-content/uploads/2014/09/1022201314344PM_635_nokia-Lumia-1520.jpeg"
},
{
"post_title": "breaking news1",
"post_content": "Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, ",
"post_image": "http://localhost/police/wp-content/uploads/2014/09/breaking_news.jpg"
},
{
"post_title": "breaking-news",
"post_content": "The first line of Lorem Ipsum, “Lorem ipsum dolor sit amet..”, comes from a line in section 1.10.32. ",
"post_image": "http://localhost/police/wp-content/uploads/2014/09/breakingNews.jpg"
}
]
}


In the above result, all posts in all categories are displayed in individual requests data, but i want to get the output in same data request.i'm using the json format first time.So i'm in need!!Help me!!

Answer Source

Few points to note:

1. You dont want to echo json strings in the loop.

What you need to do is to make a proper associative array in the for loop. And once it is made via the loop and loop completes, you can json_encode the complete associative array and echo it.

2. improper use of $jsonposts variable

In the code you have quoted, the $jsonposts variable is used internally in the loop to make individual post arrays which are displayed immediately. It can be declared when you need it. That is inside the loop. Also you can have a global array (I have put op in the code) to which you could push each element of the complete output in the loop iterations and finally encode it ad send.

3. proper code indentation

please indent the code properly so that I would be helpful to understand the flow when you read it at a later stage or provide to others for support.

include("../wp-config.php");
header('Content-type: application/json;');

/* Use this variable for preparing the result to be send back as json response */
$op = array();

$cat_args=array(
   'orderby' => 'name',
   'order' => 'ASC'
);
$categories=get_categories($cat_args);

foreach($categories as $category) 
{
    $args=array(
     'showposts' => -1,
      'category__in' => array($category->term_id),
      'caller_get_posts'=>1
     );
    $posts=get_posts($args);
    if ($posts) {
        foreach($posts as $post) {

            /* prepare individual item to be pushed into the result array */
            $jsonpost = array();
            $jsonpost['post_title']=get_the_title();
            $jsonpost['content']=apply_filters('the_content', $post->post_content); 
            $jsonpost['image_url']=wp_get_attachment_url( get_post_thumbnail_id($id, 'thumbnail') );  
            $jsonpost['date']=get_the_date('d F Y');

            /* push the item on to the result array */
            $op[] = array('request'  => 'all_posts',
                          'data'=> $jsonpost)

        }
    } 

}
/* array should be complete at this point encode it as json string and send back */
echo json_encode($op);

update to comments below

The expected json result you are showing in question is not valid json. You may check the same via jsonlint.com. A suggestion would be to make it like

  {"request":"all_posts","data": [

    {"post_title":"Breaking News story1","content":"...."},
    {"post_title":"Breaking News story1","content":"...."},
    /* repeat elements here */

  ] }

updated to comments below

To change your code sothat it produces a JSON like the one mentioned above here. You have to make the following changes in the code mentioned above.

change the line

$op[] = array('request'  => 'all_posts',
                      'data'=> $jsonpost);

to

$op[] = $jsonpost;

and change the last line from

echo json_encode($op);

to

echo json_encode(array('request'  => 'all_posts',
                      'data'=> $op));