Code

A permission callback that checks the post, not only the role

An ability’s permission callback receives the same input as the ability itself. So it can ask whether the current user may edit this particular post, not only what role they have.

'permission_callback' => function ( $input ) {
	if ( ! current_user_can( 'edit_post', $input['post_id'] ) ) {
		return new WP_Error(
			'forbidden',
			__( 'You cannot edit this post.', 'wcgalicia' ),
			[ 'status' => 403 ]
		);
	}
	return true;
},

The check is enforced everywhere the ability can be run: a PHP call, the REST route and MCP. It is written once. Return true or false, or a WP_Error when you want to give a message and an HTTP status.

What not to do

'permission_callback' => '__return_true',

On anything that writes, this lets every caller through.

From the talk Coding the Future: A Developer’s Guide to Registering WordPress Abilities.

← All code