Code

Register your first WordPress ability

An ability is one piece of functionality with a contract a machine can read. Registered once, it can be run from PHP, over REST, from JavaScript and by AI agents. This is the smallest complete example: an ability that returns the title, excerpt and word count of a post. It needs WordPress 6.9 or newer.

1. A category

Categories are registered on their own hook, which fires first, because a category must exist before any ability that refers to it.

add_action(
	'wp_abilities_api_categories_init',
	function () {
		wp_register_ability_category(
			'wcgalicia-content',
			[
				'label'       => __( 'WordCamp Content', 'wcgalicia' ),
				'description' => __( 'Abilities for WordCamp content.', 'wcgalicia' ),
			]
		);
	}
);

2. The ability

The name is namespace/ability-name: lowercase, with dashes and no underscores. The description is not a comment: an AI agent reads it to decide whether this is the right tool.

add_action( 'wp_abilities_api_init', function () {
	wp_register_ability( 'wcgalicia/get-post-summary', [
		'label'               => __( 'Get post summary', 'wcgalicia' ),
		'description'         => __( 'Returns title, excerpt and word count of a post.', 'wcgalicia' ),
		'category'            => 'wcgalicia-content',
		'input_schema'        => [
			'type'       => 'object',
			'properties' => [
				'post_id' => [
					'type'        => 'integer',
					'minimum'     => 1,
					'description' => 'ID of the post to summarize.',
				],
			],
			'required'             => [ 'post_id' ],
			'additionalProperties' => false,
		],
		'output_schema'       => [ /* title, excerpt, word_count */ ],
		'permission_callback' => fn( $input ) => current_user_can( 'read_post', $input['post_id'] ),
		'execute_callback'    => 'wcgalicia_get_post_summary',
		'meta'                => [ 'show_in_rest' => true ],
	] );
} );

3. The callback

One argument in, one result out. The input arrives already validated against the input schema, and the result is checked against the output schema.

function wcgalicia_get_post_summary( array $input ) {
	$post = get_post( $input['post_id'] );

	if ( ! $post ) {
		return new WP_Error(
			'not_found',
			__( 'Post not found.', 'wcgalicia' ),
			[ 'status' => 404 ]
		);
	}

	return [
		'title'      => $post->post_title,
		'excerpt'    => get_the_excerpt( $post ),
		'word_count' => str_word_count(
			wp_strip_all_tags( $post->post_content )
		),
	];
}

Things that go wrong

  • The wrong hook, such as init or rest_api_init: the ability silently never exists.
  • A category registered after the ability: registration returns null, with a notice only when WP_DEBUG is on.
  • Underscores in the name: rejected.
  • The output schema is strict: test what your callback returns.

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

← All code