[英]Output JSON for WordPress posts
I am using JSON-API plugin for WordPress and I am creating a custom controller that returns a list of posts from a post type. 我正在为WordPress使用JSON-API插件,并且正在创建一个自定义控制器,该控制器返回帖子类型的帖子列表。 The output I want is something like this: 我想要的输出是这样的:
[{
"id": 1,
"title": "Sample Post Title"
},
{
"id": 2,
"title": "Sample Post Title"
},
....
]
here is my custom controller: 这是我的自定义控制器:
class JSON_API_Custom_Controller {
public function get_posts_type() {
global $json_api;
$posts_all = array();
$args = array( 'post_type' => 'shopping', 'posts_per_page' => -1);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$post_id = get_the_ID();
$post_title = get_the_title($post_id);
$posts_all []= array(
'id' => $post_id,
'title' => $post_title
);
endwhile;
}
return $posts_all;
}
}
but the output is : 但输出是:
{
"status":"ok",
"0":{
"id":1,
"title":"sample title"
},
"1":{
"id":2,
"title":"sample title"
}
}
how can I output the json array of objects like the desired output? 如何输出对象的json数组,如所需的输出?
I suppose adding status:ok
to json response is a feature of a plugin. 我想将status:ok
添加到json响应是插件的功能。
So, you can modify you function to return an array with one key: 因此,您可以修改函数以使用一个键返回一个数组:
// not this
//return $posts_all;
// but this
return array('posts' => $posts_all);
After that, you will still have status
key in your json response, but also you will have posts
key, that you can iterate over. 之后,您将在json响应中仍然具有status
密钥,但是您将具有可以迭代的posts
密钥。
Update: I suppose, the filter json_api_encode
may help you. 更新:我想,过滤器json_api_encode
可以为您提供帮助。 You can unset status
key there: 您可以在此处取消设置status
键:
add_filter('json_api_encode', 'remove_status');
function remove_status($response) {
unset($response['status']);
return $response;
}
Hope the below code will do that for you. 希望下面的代码为您做到这一点。
return json_encode($posts_all);
To get that "Status" as in example output, you need to add the same in your code. 要获得示例输出中的“状态”,您需要在代码中添加相同的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.