I am trying to create a custom post using WordPress REST API. The problem is that I can create the custom post when logged in as an administrator. But when I try to create the post while logged in as a custom role 'new_role', the API is giving the below error response.
{
"code": "rest_cannot_update",
"message": "Sorry, you are not allowed to edit the letter_intro custom field.",
"data": {
"key": "letter_intro",
"status": 403
}
}
And the post get created without having the post_meta
values. I tried adding the capability by adding the below code in function.php
add_action('rest_api_init', function () {
$new_role = get_role('new_role');
$new_role->add_cap('edit_post', true);
$new_role->add_cap('edit_post_meta', true);
...
...
But it is not working.
I was able to resolve it by using the below code.
$args = array(
'labels' => $labels,
'description' => 'Custom post',
'public' => true,
'menu_position' => 5,
'supports' => array('title', 'editor', 'thumbnail', 'author', 'excerpt', 'comments', 'custom-fields'),
'has_archive' => true,
'show_in_rest' => true,
'rest_base' => 'letters',
'capabilities' => array(
'edit_post' => 'edit_letter',
'edit_posts' => 'edit_letters',
'publish_posts' => 'publish_letters',
'read_post' => 'read_letter',
'delete_post' => 'delete_letter'
),
);
register_post_type('letter', $args);
Then add those capabilities to the required roles.
function new_caps()
{
$new_role = get_role('new_role');
$new_role->add_cap('edit_letter', true);
$new_role->add_cap('edit_letters', true);
$new_role->add_cap('publish_letters', true);
$new_role->add_cap('read_letter', true);
$new_role->add_cap('delete_letter', true);
$admins = get_role( 'administrator' );
$admins->add_cap('edit_letter', true);
$admins->add_cap('edit_letters', true);
$admins->add_cap('publish_letters', true);
$admins->add_cap('read_letter', true);
$admins->add_cap('delete_letter', true);
}
add_action('init', 'new_caps', 11);