Building with Abilities
Welcome to the second part of our series on developing with WordPress’s Abilities API. In Part 1: Thinking in Abilities, we introduced the concept of Abilities as functional primitives that encapsulate specific code logic behind a well-defined schema, and went through how to register and call them.
This time, we’ll be going deep into best practices around building Abilities. We’ll cover what makes a good Ability and when it makes sense to create one, and how Abilities compare and fit in with existing architectural patterns in WordPress, such as Hooks and REST endpoints. We’ll also look at common pitfalls and anti-patterns to watch out for and ways to avoid them.
Let’s dive in!
What makes a “good” Ability?
When learning about the Abilities API, it’s easy to fall into the trap of trying to wrap existing WordPress functions (e.g., wp_insert_post) or specific plugin methods in Abilities. Another common mistake is to wrap pre-existing REST endpoints in an Ability, treating the API like a convenient transport and nothing more. Jargon like “functional primitives” and “composable units of encapsulated logic” doesn’t really tell you what logic deserves to be encapsulated or where to draw the boundaries. Abilities are very versatile, and it’s easy to adopt anti-patterns that can lead to brittle, unmaintainable code.
Keeping in mind that the purpose of Abilities are to create reliable and reusable functionality, we can evaluate them based on a the following primary criteria:
- Does this functionality need to be reused in multiple contexts?
If the answer is “no”, then it doesn’t need to be an Ability. Ask the question both in the context of downstream and 3rd-party integrations – “Is this something other codebases should be able to use reliably” – and your own codebase. Will multiple domains in your plugin need to perform this action, or will you want (yourself or others) to be able to trigger this from REST, WP-CLI, GraphQL, or another transport layer? If so, encapsulating it in an Ability will keep your code DRY and reduce the amount of usage-specific maintenance you need to keep up.
- Does this functionality benefit from encapsulation?
The Abilities API isn’t meant to replace every function or OOP class in your codebase. A single function that performs a simple task with a strict method signature doesn’t need a permission model or metadata. And while it might be tempting to lean into the DX benefits of an Ability, unless there’s a strong reusability concern, you’ll get more mileage if you skip the overhead and just adopt a Result control pattern for your internal code and return
Well-designed Abilities are those that perform a single, distinct, outcome-oriented task that may involve multiple programmatic steps, i.e. function calls and method invocations. They are the “verbs” of your codebase, the things that get stuff done. Looking back to our PDF Generator example from Part 1,value|WP_Errorfrom that function.rt-plugin/generate-pdfisn’t just an interface for callingTCPDFto create a physical file. Hypothetically at least, it also checks if an existing PDF is accessible for the user, maps the provided frontend URL to the object type, and coerces the data into the right shape for the underlying PDF library, creates the PDF, saves it somewhere safe inwp-content, and then returns the URL to the generated file. Traditionally, a change to any one of those steps – or the direct use of any of those functions outside that specific flow – could cause a snowball of downstream changes and new edge cases. By wrapping it all in a single Ability, now all those steps are implementation details and can be changed, refactored, or otherwise iterated on without worrying about downstream consequences.Mostly. Which brings us to…
- How messy are the side effects?
Just because you might want to reap the benefits of reuse and encapsulation doesn’t mean the functionality can be encapsulated in a way that is deterministic and safe to call from multiple contexts. When functionality has “side effects” that changes the state of values outside of its own scope, it becomes harder to ensure that it can be reused without unintended consequences. While it’s not always possible or desirable to have a “pure” Ability with idempotent behavior and no side effects, the more you can minimize and control for them, the better off you’ll be. And if you can’t, then it might be a sign that this functionality isn’t a good candidate for an Ability at all.
Taken together, these criteria should help you draw the boundaries around which parts of your codebase should be corralled into an Ability and which should be internal implementation details or left totally outside it. Let’s see where Abilities fit in the WordPress architecture and how they compare to other architectural patterns in our toolkit.
Abilities versus…
Actions
Actions provide a way to hook into specific points in the WordPress execution flow to trigger custom code. Abilities are the code, and can either be triggered in response to an Action or trigger their own action.
Here’s an example of the former, where we trigger an Ability in response to the save_post action:
/**
* Generate a PDF when a post is saved.
*
* In traditional WordPress, we can't always trust type safety so we don't hardcode our callback signature and instead
* rely on doctypes and linting.
*
* @param int $post_id The post ID.
* @param \WP_Post $post The post object.
*
* @return void
*/
add_action( 'save_post', static function ( $post_id, \WP_Post $post ) ) {
// Bail if the post isn't published.
if ( 'publish' !== $post->post_status ) {
return;
}
$uri = wp_make_link_relative( (string) get_permalink( (int) $post_id ) );
$ability = wp_get_ability( 'rt-plugin/generate-pdf' );
$pdf_data = $ability instanceof \WP_Ability ? $ability->execute( ['url' => $uri ] ) : new \WP_Error( 'ability_not_found', 'The requested ability was not found.' );
// Let the devs know if something went wrong.
if ( is_wp_error( $pdf_data ) ) {
// Pretend this is a real function, and an inline not a callback.
_doing_it_wrong( __FUNCTION__, sprintf( 'PDF generation failed: %s', $pdf_data->get_error_message() ), '1.0.0' );
}
}, 10, 2 );
And here’s an example of the latter, where we trigger an Action from within an Ability:
// ... rest of the Ability registration code
'execute_callback' => static function ( array $input ): array|\WP_Error {
// The rest of the callback...
/**
* Triggers on successful PDF generation.
*
* @param string $pdf_url The URL of the generated PDF.
* @param int $attachment_id The attachment ID of the generated PDF.
* @param array<string,mixed> $pdf_data The generated PDF file metadata.
* @param array<string,mixed> $input The original input passed to the Ability.
*/
do_action( 'rt_plugin/ui/pdf/generated', $pdf_url, $attachment_id, $pdf_data, $input );
return $pdf_data;
},
// ...
/**
* Elsewhere in our codebase.
*
* (We trust the action parameters types because we defined them strictly ourselves.)
*/
add_action( 'rt_plugin/ui/pdf/generated', static function ( string $pdf_url, int $attachment_id, array $pdf_data, array $input ) {
if ( empty( $pdf_url ) || empty( $attachment_id ) || empty( $pdf_data['file'] ) ) {
return;
}
// Do something with the generated PDF, e.g. log it, send an email, etc.
if ( wp_is_development_mode( 'plugin' ) ) {
error_log( sprintf( 'PDF generated: %s (Attachment ID: %d)', $pdf_url, $attachment_id ) );
}
// You can even chain another ability.
$offload_ability = wp_get_ability( 'rt-plugin/offload-to-s3' );
if ( ! $offload_ability instanceof \WP_Ability ) {
// If s3 isn't available, no need to offload it.
return;
}
$offload_result = $offload_ability->execute( [
'attachment_id' => $attachment_id,
'file_path' => $pdf_data['file'],
] );
if ( is_wp_error( $offload_result ) ) {
error_log( sprintf( 'Failed to offload PDF to S3: %s', $offload_result->get_error_message() ) );
}
} );
Filters
Filters provide a way to modify data at specific points in the WordPress execution flow. Similar to Actions (Actions are just Filters that return void), Abilities can use and be used by Filters – in a few fun ways, like swapping out abilities:
// Source code somewhere:
/**
* Swap out the PDF Generator with a compatible one.
*
* @param string $ability_name The original ability name.
* @param array<string,mixed> $input The input to pass to the ability.
* @return string The ability name to execute.
*/
$ability_name = apply_filters( 'rt-plugin/ui/pdf/generate_ability_name', $ability_name, $input );
$pdf_data = $this->execute_ability( $ability_name, $input );
// Elsewhere...:
add_filter( 'rt-plugin/ui/pdf/generate_ability_name', static function ( string $ability_name, array $input ) : string {
// Maybe we want to use a different PDF generator for certain users, or based on the content of the PDF.
if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
return 'rt-plugin/generate-pdf-pro';
}
// Or maybe we want to swap out the PDF generator for certain types of content.
if ( ! empty( $input['content_type'] ) && 'product' === $input['content_type'] ) {
return 'third-party/generate-product-pdf';
}
return $ability_name;
}, 10, 2 );
Or, modifying the Ability’s input/output:
// Source code somewhere:
/**
* Modify the input for the PDF Generator.
*
* @param array<string,mixed> $input The original input.
*/
$input = apply_filters( 'rt-plugin/ui/pdf/generate_input', $input );
/**
* Used to shortcircuit the PDF generation if certain conditions are met.
* @param array<string,mixed>|null $pre The preemptive result. If this is not null, the ability execution will be shortcircuited and this value will be returned instead.
* @param array<string,mixed> $input The filtered input.
*/
$pre = apply_filters( 'rt-plugin/ui/pdf/pre', $pre, $input );
if ( null !== $pre ) {
return $pre;
}
$ability = wp_get_ability( 'rt-plugin/generate-pdf' );
$output = $ability instanceof \WP_Ability ? $ability->execute( $input ) : new \WP_Error( 'ability_not_found', 'The requested ability was not found.' );
/**
* Modify the output of the PDF Generator.
*
* @param string|\WP_Error $output The original output.
* @param \WP_Ability $ability The ability instance.
* @param array<string,mixed> $input The original input.
* @return string|\WP_Error The modified output.
*/
return apply_filters( 'rt-plugin/ui/pdf/output', $output, $ability, $input );
// Elsewhere...:
add_filter( 'rt-plugin/ui/pdf/input', static function ( array $input ) : array {
// Maybe we want to add some additional data to the input based on the content type.
if ( ! empty( $input['content_type'] ) && 'product' === $input['content_type'] ) {
$args = $input['product_id'] ? [
'by' => 'product_id',
'id' => (int) $input['product_id'],
] : [
'by' => 'user_id',
'id' => get_current_user_id(),
];
$coupons = wp_get_ability( 'rt-plugin/get-product-coupon-recommendations' )?->execute( $args ) ?? [];
if ( ! $coupons instanceof \WP_Error ) {
$input['coupons'] = $coupons;
}
}
return $input;
} );
// Or
add_filter( 'rt-plugin/ui/pdf/pre', static function ( ?array $pre, array $input ) : ?array {
// Maybe some content types have a "real" PDF.
if ( ! empty( $input['content_type' ] ) && 'magazine' === $input['content_type'] ) {
current_user_can( 'view_magazine_pdf' ) ? $pre = \Rt_Plugin\Magazine\PDF::get_pdf_for_post( $input['id'] ) : $pre = new \WP_Error( 'permission_denied', 'You do not have permission to view this PDF.' );
}
return $pre;
} );
add_filter( 'rt-plugin/ui/pdf/output', static function ( array|WP_Error $output, array $input ) : array|WP_Error {
// If it took too long to generate, offload it to a background process and return a "processing" status.
if ( is_wp_error( $output ) && $output->get_error_code() === 'pdf_generation_timeout' ) {
// PS: Action Scheduler actions can also be designed to wrap Abilities.
as_schedule_single_action( time(), 'rt-plugin/generate-pdf-background', [ 'input' => $input ] );
return \Rt_Plugin\PDF_Generator\Config::get_placeholder_pdf_url();
}
return $output;
} );
As we saw with Actions, these Filter patterns could work just as well inside an Ability’s execute_callback and can even be used as a form of dependency injection to provide malleability within the Ability itself while maintaining the strict isolation layer surrounding it.
'execute_callback' => static function ( array $input ): bool|\WP_Error {
// The rest of the callback...
$pdf_renderer_class = apply_filters( 'rt-plugin/pdf_renderer_class', \Rt_Plugin\PDF_Generator\TCPDF_Renderer::class, $input );
$pdf_blob = ( new $pdf_renderer_class() )->render( $pdf_data );
// ... rest of the callback
},
Transport Layers (REST, WP-CLI, GraphQL, etc.)
REST endpoints, WP-CLI commands, GraphQL resolvers, and other transport layers are the interfaces that marshal data from the outside world into your codebase. They are the “controllers” in an MVC analogy, and as such should be as thin as possible. Traditionally, developers do their best to keep business logic out of these layers in OOP classes, but it’s easy for things to creep and become brittle as you try and support more and different contexts. Abilities’ enforced contracts keep that creep at bay and make it easier to maintain – and abstract away – the transport layer from the core logic.
You can see an example of this in WordPress’s own WP_REST_Abilities_V1_Run_Controller class which is a generic REST Adapter for executing any Ability. All it does is takes the incoming REST request, and then based on the ability name, validates the input against the Ability’s registered schema and then executes it. The REST endpoint doesn’t need to know anything about the specific logic of any Ability, and all the business logic lives safely within the Abilities themselves.
Let’s look at a concrete example of how we would register a REST endpoint for our rt-plugin/generate-pdf:
/**
* {@inheritDoc}
*
* Registers the REST route for generating a PDF.
*/
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
[
'methods' => \WP_REST_Server::CREATABLE,
'args' => [
// Our REST API is used for our internal UX, we don't want to expose all the Ability Inputs.
'id' => [
'type' => [ 'integer' ],
'description' => __( 'The ID of the object to generate a PDF for.', 'rt-plugin' ),
'required' => true,
'validate_callback' => 'is_numeric',
],
'content_type' => [
'type' => [ 'string' ],
'description' => __( 'The type of the object to generate a PDF for (e.g., post, product, etc.).', 'rt-plugin' ),
'enum' => $this->get_supported_content_types(), // This could be a method that returns ['post', 'product', 'user'] or whatever content types you support.
'required' => true,
'validate_callback' => static function ( $value ) {
return in_array( $value, [ 'post', 'product', 'user' ], true );
},
],
],
'callback' => function ( \WP_REST_Request $request ) {
$input = $this->map_params_to_ability_input( $request->get_params() );
if ( $input instanceof \WP_Error ) {
return new \WP_REST_Response( [ 'error' => $input->get_error_message() ], 400 );
}
$ability = wp_get_ability( 'rt-plugin/generate-pdf' );
if ( ! $ability instanceof \WP_Ability ) {
return new \WP_REST_Response( [ 'error' => __( 'Ability not found.', 'rt-plugin' ) ], 404 );
}
$result = $ability->execute( $input );
if ( is_wp_error( $result ) ) {
return new \WP_REST_Response( [ 'error' => $result->get_error_message() ], 500 );
}
return new \WP_REST_Response(
[
'pdf_url' => $result['pdf_url'],
'attachment_id' => $result['attachment_id'],
],
200
);
},
'permission_callback' => [ $this, 'create_item_permissions_check' ],
'schema' => [ $this, 'get_item_schema' ],
]
);
}
As you can see, the REST endpoint is just responsible for validating and mapping what’s needed for the particular use case, e.g. showing a “Generate PDF” button in the UI that displays an embedded PDF preview after the endpoint returns. You don’t need to worry about the internal Ability logic changing on you, and you’re similarly free to iterate on the REST endpoint (e.g. show the filesize, add additional parameters, etc.) independently of the core PDF generation logic.
PHP Classes and APIs
Abilities are non-prescriptive about how you implement the internal logic and you can still use PHP classes, OOP patterns, and any other architectural patterns you like within the execute_callback. Similarly, you can wrap abilities in global functions or use them in abstract classes or as injected dependencies in your service container. Abilities can also exist alongside traditional procedural code and PHP APIs.
The biggest difference between relying on an ability versus just calling a PHP class method or function directly is the trust that comes from the schema contract. Your downstream code gets predictable handling and outputs when using your Ability, and remains insulated from what would otherwise be breaking changes. You get WP_Error handling, known inputs and outputs, and a protective wall against everything from well-meaning refactors to vibe-coded slop that made it past code review. Even if the broader WordPress ecosystem followed good release hygiene, SemVer is still nothing more than a promise. Ability schemas can be introspected and validated at runtime, with tools to automate checking for breaking changes forthcoming in the future.
Handling State and Side Effects
As mentioned above, Abilities work best when they’re stateless and idempotent, but that’s not always practical when dealing with WordPress code. The key is to be intentional and mindful about the side effects and state changes your Ability might have.
For example, if your Ability creates a new post, that’s a side effect that changes the state of the database. That’s not necessarily a problem, but you need to be aware of it and design your Ability accordingly. You might want to make sure that if the same input is passed multiple times, it doesn’t create duplicate posts. What matters is that you’re intentional about it.
Whenever possible, your Abilities should do their best to avoid relying on WordPress globals. Ideally, they shouldn’t rely on any global state at all, and have all the data they need passed in through the input. If you’re dealing with legacy code that relies on globals, you can use a ::set_up()/::tear_down() pattern to wrap the legacy code to keep things contained. For example:
// ...
'execute_callback' => static function ( array $input ): array|\WP_Error {
$this->setup_globals( $input );
$result = \My_Legacy_Code::do_thing_that_needs_global_state( $input );
$this->tear_down_globals();
return $result;
},
...
/**
* Set up the globals for the legacy code to run.
* @param array<string,mixed> $input The input passed to the Ability.
*/
private function setup_globals( array $input ) : void {
// Set up any globals needed for the legacy code to run.
global $post;
$this->original_post = $post;
$post = get_post( $input['post_id'] );
// etc.
}
/**
* Tear down the globals after the legacy code has run.
*/
private function tear_down_globals() : void {
// Restore any globals to their original state.
global $post;
$post = $this->original_post;
// etc.
}
Similar patterns, like try/catch/finally blocks, or storing ability state in a Transient to cross the single-execution boundary, can also be used to manage side effects while keeping your Abilities as deterministic as possible, but the complexity increases the more you try to manage, and you’re left with a brittle API that’s as bad as the legacy code you were trying to call. So again, the key is to be intentional about it.
That said, nothing scales better than passing your state through your Ability as input and output. If you find yourself needing to manage a lot of state or side effects, it’s worth taking a step back and asking if there’s a way to refactor your code to be more functional and pass the state through the Ability instead. It might require more upfront work, but it will pay off in the long run with more maintainable and reusable code.
Next Time: Designing Ability Schemas
In this article, we went through the different considerations and ways to build Abilities, and how and when to use them alongside other architectural patterns in WordPress. We spoke a lot about statelessness and noted the importance of well-designed input and output schemas, but we haven’t actually spoken about how to design those schemas yet.
In the next post, we’ll be providing a crash course in scalable API design, and show you how to shape your abilities schemas for maximum reusability and robustness. We’ll cover what makes a good input or output schema and how to handle errors and edge cases in your schema, how to plan for forward-compatibility, and then teach you how to evolve the schema without breaking backward-compatibility when all the planning gets thrown out the window. We’ll walk through the versioning anti-pattern and show you what you can do instead.
We’re about halfway through the series now, and it’s only getting more technical from here. Stay hydrated, and see you next time!







