I have set up a custom post type CRM in Wordpress. I was positively surprised that it appeared with it's own model in Wordpress's Backbone API thing. I really wanted to get to understand it, but I've run into a wall here.
I have 2 posts of the aforementioned custom post type saved into WP. Here's an example of what I try to do:
var crm = new wp.api.models.Crm();
crm.fetch().then(function(crmItems){
console.log(crmItems);
});
Works great, fetches both posts. They are the correct post type and all. Everything fine, really.
Then another test:
var crm = new wp.api.models.Crm({id: 6257});
crm.fetch().then(function (crmItems) {
console.log(crmItems);
});
This too works as expected, returns one post. All fine.
But then:
var crm = new wp.api.models.Crm({data: {per_page: 1}});
crm.fetch().then(function (crmItems) {
console.log(crmItems);
});
This one is supposed to return only one post, yet it returns both. I copied the parameters from the documentation and only changed the number from 25 to 1. I found the request in Firefox's dev tools, the network tab. The request URL is https://[my-site]/wp-json/wp/v2/crm
No parameters are sent. That's weird. Shouldn't the request URL look something like https://[my-site]/wp-json/wp/v2/crm?per_page=1
? Pasting that URL into the address bar works fine and returns just one post, as expected.
Furthermore, I learned to add meta fields to the return objects, like so:
add_action('rest_api_init', function () {
$fields = array('visibility');
foreach ($fields as $field) {
register_rest_field('crm', $field, array(
'get_callback' => function ($params) use ($field) {
return get_post_meta($params['id'], $field, true);
}, 'updata_callback' => function ($value, $object, $fieldName) {
return update_post_meta($object->ID, $fieldName, $value);
},'schema' => array(
'description' => __( 'Visibility.' ),
'type' => 'string'
)
));
}
});
The field shows up, all right, but I have not been able to find a good guide that would help me to understand how to filter the collection fetch using this field. How is it done?