Resolved ?? Find the solution below:
We will need to use the filter json_prepare_post
with higher priority so we run our filter after all other filters.
/*
code requires php 5.3+
*/
// the filter
add_filter('json_prepare_post', 'numstock_json_prepare_post', 100);
function numstock_json_prepare_post($post){
$mapper = new \Numstock\Models\DataMappers\Post_to_Object($post);
$post = $mapper->map();
return $post;
}
// the data mapper class put in a different file
namespace Numstock\Models\DataMappers;
class Post_to_Object{
public $post = null;
public $map = array(array('ID' => 'id'), 'title', 'content', 'date');
public function __construct($post){
$this->post = $post;
}
public function map(){
$mapped = array();
$map = $this->map;
foreach($map as $key){
if(is_array($key)){
foreach($key as $k => $v){
$mapped = $this->set_data($k, $mapped, $v);
}
continue;
}
// no an array
$mapped = $this->set_data($key, $mapped);
}
return $mapped;
}
public function set_data($k, $mapped, $v = false ){
$post = $this->post;
if(!$v){
$v = $k;
}
if( array_key_exists($k, $post) ){
$mapped[$v] = $post[$k];
}
return $mapped;
}
}
Output
———
[
{
"id":21,
"title":"Test Post",
"content":"<p>This is a test<\/p\n",
"date":"2014-12-14T10:51:11+00:00"
}
]
**Note:** I needed to remap the WordPress default ID
as id
. But basically you just create an array with the keys you want as output and return it from filter.