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.
Hi, can you little more explaint this? where i can paste filter code? and how look request?
THX a lot
Kanif
(@kaniffattepurkar)
Hi, We are facing same problem on where to add this code. Can you please explain more on this.
Thanks in advance.
Hi,
@raba and Kanif, did you finally found where to put prionkor’s script?
Grts,
Mario
Hi all, sorry I have missed previous notifications.
Just put the first part of the code in functions.php if using theme. If it is a plugin put it on plugin file.
Make a new php file and put the class in it. and require the class from functions.php or the plugin file.