Scaling with Abilities
Welcome to the fourth part of our series on developing with WordPress’s Abilities API.
In Part 1: Thinking in Abilities, we introduced Abilities as functional primitives that let you rely on other code without caring how it’s implemented. In Part 2: Building with Abilities, we explored what makes a good Ability and explained how and when to use them. In Part 3: Designing Ability Schemas, we focused on best practices for shaping, structuring, and evolving Ability schemas so they stay flexible and maintainable over time.
So far, we’ve mostly looked at Abilities in isolation. In this article, we’ll be looking at advanced techniques for using the Abilities API to solve complex problems faced when using Abilities at scale.
We’ll borrow the commerce examples from Part 3 in places, but as before, they’re primarily illustrative.
Let’s get started!
Composing Abilities into Workflows
We previously created an rt-commerce/place-order Ability with roughly the following shape:
/**
* rt-commerce/place-order
*
* Places an order and charges the customer.
*
* Input:
* customer: { user_id } | { email, name }
* items: [ { product: { id } | { sku }, quantity } ]
* coupons?: [ { code } ]
* fulfillment: { method: 'shipping', address } | { method: 'none' }
* payment: { method, token?, billing_address? }
*
* Output:
* order: { id, status, customer, items, totals, payment, fulfillment, receipt_url }
* errors: [ { code, message, path, data } ]
* next_action: { ability_name, input } | null
*
* Errors: insufficient_stock, invalid_coupon, payment_declined
*/
As we wrote there, part of the reason for returning the full order was so the result could be handed straight to the next Ability. For example:
$order_input = [
'customer' => // from wp_get_ability( 'rt-commerce/get-customer' )->execute(...),
'items' => [ /* ... */ ] // from wp_get_ability( 'rt-commerce/validate-cart-items' )->execute(...),
'payment' => [ 'method' => 'card', 'token' => /* ... */ ], // from wp_get_ability( 'rt-commerce/process-payment' )->execute(...),
// ... etc.
];
$result = wp_get_ability( 'rt-commerce/place-order' )->execute( $order_input );
if ( is_wp_error( $result ) ) {
return $result;
}
$order_sent = wp_get_ability( 'rt-commerce/send-order-confirmation' )->execute( [ 'order_id' => $result['order']['id'] ] );
$rendered = wp_get_ability( 'rt-commerce/render-order-confirmation' )->execute( [ 'order_id' => $result['order']['id'] ] );
// ... etc.
The splits may seem arbitrary at first, or even obvious in hindsight, but they allow each Ability to focus on a single responsibility, a self-contained “step” in the overall “workflow”. The more granular the steps, or the more overlapping the responsibilities are, the more “complex” the workflow becomes, so we’re still motivated to limit our Abilities to self-contained outcomes, and not break them into fragments unnecessarily. We can determine an appropriate number of steps by mapping out the sequence of actions required to complete a task and identifying the distinct units of work that can be encapsulated as individual Abilities. We rely on the encapsulation and standardization of our input and output schema shapes to make it easier to change or replace individual steps without it affecting other Abilities in the workflow.
Encapsulating Ability chains
Something has to call those Abilities and decide what to do with each result. It’s tempting to wrap the whole chain in an Ability of its own, but in many cases that just adds a layer of abstraction you don’t need. Instead, keep the chain as close to its caller as possible. Our checkout Abilities might be consumed by:
- A REST or CLI endpoint, as a thin transport layer for syncing orders with an ERP.
- A render layer, powering your storefront templates.
- A set of WebMCP tools, powering an agentic commerce flow.
- A plain PHP function or class, enforcing separation of concerns between modules or codebases.
Each of those wants something slightly different from the same Abilities. Our “storefront” example above places an order, renders the confirmation, and sends it to the customer.
The ERP sync places the same orders, but there’s nothing to render, and some customers may have already received their confirmations from the old system.
// wp rt-commerce import-orders
foreach ( $erp_orders as $erp_order ) {
$result = wp_get_ability( 'rt-commerce/place-order' )->execute( rt_commerce_map_erp_order( $erp_order ) );
if ( is_wp_error( $result ) ) {
WP_CLI::warning( sprintf( 'Skipping %s: %s', $erp_order['ref'], $result->get_error_message() ) );
continue;
}
if ( $erp_order['needs_confirmation'] ) {
$order_sent = wp_get_ability( 'rt-commerce/send-order-confirmation' )->execute( [ 'order_id' => $result['order']['id'] ] );
if ( is_wp_error( $order_sent ) ) {
WP_CLI::warning( sprintf( 'Failed to send confirmation for %s: %s', $erp_order['ref'], $order_sent->get_error_message() ) );
continue;
}
}
// Update some external state.
$this->mark_success( $erp_order['ref'], $result['order']['id'], ...$other_state );
}
The more paths you need to handle, the harder it becomes to encapsulate Abilities into a coherent workflow, with problems like state management, error handling, and schema coordination all exacerbating each other. By optimizing for a “flat” shape, and leaving the implementation details for each path to be handled locally, you reduce the overall complexity significantly.
That doesn’t mean you won’t benefit from the patterns discussed in this article, and in most cases these are just as applicable in a last-mile consumer context as they are in a nested Ability’s execute_callback().
Handling (and recovering from) Errors
When handling simple Abilities, there’s usually a single outcome: it worked or it didn’t. In the last article, we briefly discussed why it’s important to differentiate between a WP_Error state and partially successful outcomes, but when discussing Ability chains, we need to account for multiple points of failure and the possibility of partial success at each step. This requires careful error handling and recovery strategies to ensure that the overall workflow remains consistent and reliable.
The easiest way to handle multiple “non-fatal” errors is with an error aggregator that collects all the problems encountered during the execution of the workflow, saving them for later examination and potential recovery. For example:
$result = wp_get_ability( 'rt-commerce/place-order' )->execute( $order_input );
// If the order wasn't placed successfully, we can't proceed.
if ( is_wp_error( $result ) ) {
return $result;
}
// Attempt to award loyalty points for the customer. This is a non-critical step and failures here should not block the main order flow.
$points = wp_get_ability( 'rt-commerce/award-loyalty-points' )->execute( $points_input );
if ( is_wp_error( $points ) ) {
$errors[] = [
'code' => $points->get_error_code(),
'message' => $points->get_error_message(),
'ability' => 'rt-commerce/award-loyalty-points',
'data' => [ 'input' => $points_input ]
];
}
$order_sent = wp_get_ability( 'rt-commerce/send-order-confirmation' )->execute( [ 'order_id' => $result['order']['id'] ] );
if ( is_wp_error( $order_sent ) ) {
$errors[] = [
'code' => $order_sent->get_error_code(),
'message' => $order_sent->get_error_message(),
'ability' => 'rt-commerce/send-order-confirmation',
'data' => [ 'input' => [ 'order_id' => $result['order']['id'] ] ]
];
}
Now, depending on your consumer, either of these failing might present as an “error”:
if ( ! empty( $errors ) ) {
return new WP_Error( 'checkout_errors', __( 'There were errors during the checkout process.', 'rt-commerce' ), $errors );
}
Or, maybe they’re handled elsewhere, such as being displayed to the user on the frontend:
$rendered = wp_get_ability( 'rt-commerce/render-order-confirmation' )->execute( [
'order_id' => $result['order']['id'],
'processing_errors' => $errors ?? null, // Outputs "Could not award loyalty points" or "Could not send order confirmation" if those steps failed.
] );
Or have special error handling for certain errors, or even try to recover entirely:
switch ( $errors[0]['code'] ?? null ) {
case 'loyalty_points_error':
// Notify staff to manually award loyalty points.
break;
case 'order_confirmation_error':
// Attempt to resend order confirmation.
break;
default:
// Handle other errors or do nothing.
break;
}
This is also a good opportunity to make what your Abilities return more actionable downstream. Alongside any errors, you could suggest a next_action, for example which Ability to call next and with what input, to recover from a specific failure. Passing $errors up the chain for centralized handling, alongside detailed return objects needed to take action later, ensures that your application can respond appropriately to different failure scenarios:
do {
$action = $result['next_action'] ?? null;
if ( ! $action ) {
break;
}
if ( ! wp_has_ability( $action['ability_name'] ) ) {
break; // Or 'continue' if this is nested inside an outer foreach/while loop
}
$success = wp_get_ability( $action['ability_name'] )->execute( $action['input'] );
if ( is_wp_error( $success ) ) {
$errors[] = [
'code' => $success->get_error_code(),
'message' => $success->get_error_message(),
'ability' => $action['ability_name'],
'data' => [ 'input' => $action['input'] ]
];
break;
}
$result = $success;
} while ( isset( $result['next_action'] ) );
This pattern is particularly useful for agentic workflows, where actions may be taken autonomously by the system and we want to guide the flow of execution more efficiently. It also hands part of your workflow’s control to the Abilities themselves, so if you’re relying on external Abilities, you might want some extra guardrails:
// Only abilities with this shape should be allowed at this point.
$allowed_recovery = [ 'rt-commerce/send-order-confirmation', 'rt-commerce/award-loyalty-points' ];
// Prevent infinite loops.
$attempts = 0;
do {
$action = $result['next_action'] ?? null;
if ( ! $action || ++$attempts > 3 || ! in_array( $action['ability_name'], $allowed_recovery, true ) ) {
break;
}
// ...the rest of the loop is unchanged.
} while ( isset( $result['next_action'] ) );
Multi-step and long-running Workflows
So far, our workflows all run inside a single request. In enterprise realities, many workflows are multi-step. Importing two million orders won’t finish within PHP’s execution limit. Multi-factor authentication sends the user to complete verification. And some steps aren’t the current user’s to perform at all: the customer places the order, but it’s the store that sends it to the warehouse, and we need to wait for that result before proceeding.
Take 3-D Secure, for example. When place-order comes back with requires_action, we need to redirect the customer to their bank and end the current request, discarding the previous $result and $errors objects with it, so when the customer returns there’s nothing to resume from. Since Abilities are stateless by default, we need to persist and manage the state ourselves.
Externalizing State
The simplest place for our state to live is inside a transient. We give the entire workflow a unique ID, and once the specific “step” Ability completes, we save what we have:
$checkout_id = wp_generate_uuid4();
// ... other code ...
$result = wp_get_ability( 'rt-commerce/place-order' )->execute( $order_input );
// As before, bail early if there's no way to recover.
if ( is_wp_error( $result ) ) {
return $result;
}
// Save what we know:
set_transient( "rt_checkout_{$checkout_id}", [
'result' => $result,
'errors' => $errors ?? [],
], HOUR_IN_SECONDS ); // How long to keep the state for.
When the customer comes back, we can retrieve the saved state e.g. by having passed the checkout ID to the return URL, and then proceed from where we left off:
// Get the $id from the encoded URL Parameter.
$checkout_id = isset( $_GET['checkout_id'] ) ? sanitize_key( wp_unslash( $_GET['checkout_id'] ) ) : '';
$current_state = get_transient( "rt_checkout_{$checkout_id}" );
The problem with using a transient is that the expiration timeout is the maximum time the state will be kept, but it could be evicted earlier if WordPress or your caching layer decides to clear it. The solution for more reliable persistence is to store the state in a wp_options entry for simple storage, or even a custom database table for high-traffic and complex storage needs. Either way, you’ll need to implement a mechanism to clean up old state entries once they are no longer needed.
Running Abilities step by step
Now that we know where we can persist the state between individual Abilities in a Workflow, let’s update our orchestration loop to allow for step-by-step execution.
The first thing we’ll do is extract the workflow as a list of steps we can loop through:
/**
* All the possible workflow steps in the checkout process, keyed to their Ability name.
*
* @return array<string, array{
* 'prepare_input' : callable(array, ?array): array // Callback to generate the ability input based on the current context.
* 'prepare_output': callable(array, array): array // Callback to process the ability output and update the state.
* }>
*/
protected static function get_workflow_steps(): array {
return [
'rt-commerce/get-customer' => [
/**
* @param array $data The `data` from the current state.
* @param array|null $previous The previous ability's output, if any.
*
* @return array The prepared input for the ability.
*/
'prepare_input' => static fn ( array $data, ?array $previous ): array => [ 'customer' => $data['cart']['customer'] ],
/**
* @param array $state The current state before processing the ability output.
* @param array $result The result returned by the ability.
*
* @return array The updated state after processing the ability output.
*/
'prepare_output' => static function ( array $state, array $result ): array {
// `place-order` needs this later, so it's worth keeping.
$state['data']['customer'] = $result['customer'];
return $state;
},
],
'rt-commerce/validate-cart-items' => [
'prepare_input' => static fn ( array $data, ?array $previous ): array => [ 'items' => $data['cart']['items'] ],
'prepare_output' => static function ( array $state, array $result ): array {
$state['data']['items'] = $result['items'];
return $state;
},
],
'rt-commerce/process-payment' => [
'prepare_input' => static fn ( array $data, ?array $previous ): array => [
'payment' => $data['cart']['payment'],
'items' => $data['items'],
],
// No `prepare_output`: the payment goes straight into `place-order`, so there's nothing to keep.
],
'rt-commerce/place-order' => [
'prepare_input' => static fn ( array $data, ?array $previous ): array => [
'customer' => $data['customer'],
'items' => $data['items'],
'fulfillment' => $data['cart']['fulfillment'],
'payment' => $previous['payment'], // Straight from `process-payment`.
],
'prepare_output' => static function ( array $state, array $result ): array {
$state['data']['order_id'] = $result['order']['id'];
// 3-D Secure: `place-order` suggests `confirm-payment` as its `next_action`, but the customer has to confirm with their bank first.
if ( 'requires_action' === $result['order']['payment']['status'] ) {
$state['status'] = static::STATUS_PENDING;
$state['data']['customer_action'] = $result['order']['payment']['next_action'];
}
return $state;
},
],
'rt-commerce/confirm-payment' => [
'prepare_input' => static fn ( array $data, ?array $previous ): array => [ 'order_id' => $data['order_id'] ],
'prepare_output' => static function ( array $state, array $result ): array {
// Still not confirmed, so wait and check again when we resume.
if ( 'paid' !== $result['payment']['status'] ) {
$state['status'] = static::STATUS_PENDING;
$state['next_action'] = 'rt-commerce/confirm-payment';
}
return $state;
},
],
'rt-commerce/award-loyalty-points' => [
'prepare_input' => static fn ( array $data, ?array $previous ): array => [ 'order_id' => $data['order_id'] ],
],
'rt-commerce/send-order-confirmation' => [
'prepare_input' => static fn ( array $data, ?array $previous ): array => [ 'order_id' => $data['order_id'] ],
],
'rt-commerce/send-to-fulfillment' => [
'prepare_input' => static fn ( array $data, ?array $previous ): array => [ 'order_id' => $data['order_id'] ],
],
];
}
With the steps abstracted, we can now run a fairly generic orchestration loop to iterate over each step:
protected static function run_workflow( string $workflow_id, array $steps, $initial_context = [] ): array {
$option_key = static::WORKFLOW_OPTION_PREFIX . $workflow_id;
// Pick up where we left off, or start a new workflow.
$state = get_option( $option_key, [
'id' => $workflow_id,
'next_action' => null,
'data' => [],
'errors' => [],
] );
// Whatever the caller passes in takes precedence over what we stored.
$state['next_action'] = $initial_context['next_action'] ?? $state['next_action'];
$state['data'] = array_merge( $state['data'], $initial_context['data'] ?? [] );
$state['status'] = static::STATUS_RUNNING;
// Holds the result of the previous step.
$previous_result = $state['previous_result'] ?? null;
// The order we run the steps in, unless an Ability suggests otherwise.
$step_names = array_keys( $steps );
while ( null !== $state['next_action'] && static::STATUS_RUNNING === $state['status'] ) {
$ability_name = $state['next_action'];
// Only Abilities that are part of this workflow get to run.
if ( ! isset( $steps[ $ability_name ] ) ) {
$state['status'] = static::STATUS_FAILED;
$state['errors'][] = [
'code' => 'unexpected_next_action',
'message' => sprintf( __( '`%s` is not part of this workflow.', 'rt-commerce' ), $ability_name ),
'ability' => $ability_name,
'data' => null,
];
break;
}
$current_step = $steps[ $ability_name ];
// Prepares the ability input per the callback.
$input = $current_step['prepare_input']( $state['data'], $previous_result );
// Execute the ability with the prepared input.
$result = wp_get_ability( $ability_name )?->execute( $input ) ?? new \WP_Error(
'ability_not_found',
sprintf( 'Ability not found: %s', $ability_name )
);
// Handle any failures from the ability.
if ( is_wp_error( $result ) ) {
$state['status'] = static::STATUS_FAILED;
$state['errors'][] = [
'code' => $result->get_error_code(),
'message' => $result->get_error_message(),
'ability' => $ability_name,
'data' => [
'input' => $input,
],
];
break;
}
// Follow the Ability's suggestion if it made one, otherwise move on to the next step in the list.
$state['next_action'] = $result['next_action']['ability_name']
?? $step_names[ array_search( $ability_name, $step_names, true ) + 1 ]
?? null;
$previous_result = $result;
$state['previous_result'] = $result;
if ( isset( $current_step['prepare_output'] ) ) {
// `prepare_output` runs last, so the workflow always gets the final say on what happens next.
$state = $current_step['prepare_output']( $state, $result );
}
// Save after every step, so if the request dies we only lose the step we were on.
update_option( $option_key, $state, false );
}
// We only "end" the workflow as completed if it was still running.
if ( static::STATUS_RUNNING === $state['status'] ) {
$state['status'] = static::STATUS_COMPLETED;
}
// Persist the external state for future requests.
update_option( $option_key, $state, false );
return $state;
}
With this approach, we could then kick off the workflow by telling which Ability and params to start with:
$checkout_status = static::run_workflow(
wp_generate_uuid4(), // New workflow, new ID
static::get_workflow_steps(),
[
'next_action' => 'rt-commerce/get-customer', // Action to start with.
'data' => [ 'cart' => $cart ] // Initial data to prime the workflow with.
]
);
The prepare_input callback gets the stored data along with the previous Ability’s result, so a step like place-order can take its payment directly from process-payment while pulling the customer and items that earlier steps saved. Meanwhile, prepare_output takes the entire $state, allowing us to pause the workflow and resume it later, while next_action tells the loop how to proceed.
For example, here’s how we can resume a workflow after 3-D Secure validates the payment:
// ...
// Resume the workflow after 3-D Secure authentication.
$workflow_id = static::get_workflow_id_from_request();
$checkout_status = static::run_workflow(
$workflow_id,
static::get_workflow_steps(),
[
'next_action' => 'rt-commerce/confirm-payment',
'data' => [] // We stored the order_id in state, but we could infer it and prime it here if needed.
]
);
And, if we’re tailoring our checkout to a specific frontend flow, we can route the user based on the workflow’s status:
switch ( $checkout_status['status'] ) {
case static::STATUS_PENDING:
// Off to an external step. The return URL we gave the payment provider includes the workflow ID, which is how `get_workflow_id_from_request()` finds it again.
wp_redirect( $checkout_status['data']['customer_action']['url'] );
exit;
case static::STATUS_FAILED:
// Back to the checkout form, with whatever went wrong.
static::redirect_to_checkout( $checkout_status['errors'] );
exit;
case static::STATUS_COMPLETED:
wp_safe_redirect( static::get_order_confirmation_url( $checkout_status['data']['order_id'] ) );
exit;
}
Moving individual steps to background or asynchronous processing should be pretty straightforward from here. We just need to indicate which steps are meant to be run asynchronously and then wire up the appropriate background processing logic, for example with Action Scheduler.
// ::get_workflow_steps()
'rt-commerce/send-order-confirmation' => [
// ... existing stuff...
'async' => true
],
// ... other steps
// ::run_workflow()
// ...
while ( null !== $state['next_action'] && static::STATUS_RUNNING === $state['status'] ) {
$ability_name = $state['next_action'];
// ...the allowlist check, as before.
$current_step = $steps[ $ability_name ];
// The first time we reach an async step, we queue it and stop. When the queued job resumes the workflow, the step is already marked as queued, so it runs.
if ( ! empty( $current_step['async'] ) && $ability_name !== ( $state['queued'] ?? null ) ) {
$state['status'] = static::STATUS_QUEUED;
$state['queued'] = $ability_name;
as_enqueue_async_action(
'rt_commerce_continue_checkout',
[ // These args are passed to the async action callback.
$workflow_id,
$ability_name,
],
'rt-commerce',
true,
);
break;
}
// ...
add_action( 'rt_commerce_continue_checkout', static function ( string $checkout_id, string $ability_name ): void {
$state = static::run_workflow(
$checkout_id,
static::get_workflow_steps(),
[
'next_action' => $ability_name,
], // Everything else is pulled from the stored workflow state.
);
// Throwing marks the action as failed, so it shows up in Action Scheduler's logs.
if ( static::STATUS_FAILED === $state['status'] ) {
throw new \Exception( end( $state['errors'] )['message'] );
}
} );
This externalizes a single Ability in a workflow, but you can easily extend this pattern to have the entire workflow run each step asynchronously.
Swapping and extending Abilities
Back in Part 3, we replaced an Ability’s stripe_token with a more generic payment.token so a hypothetical move from Stripe to Square wouldn’t require breaking changes to the schema or workflow logic. There, as above, we’re still calling one specific Ability:
$payment_status = wp_get_ability( 'rt-commerce/process-payment' )->execute( $process_payment_input );
But let’s say your multinational e-commerce store needed to sell to some regions that don’t support Square. By treating your Ability’s schema as an enforced interface, you could swap out the underlying implementation on the fly, without touching the rest of your workflow logic:
// ... rest of workflow logic.
/**
* Filter the ability name for processing payment.
*
* All abilities must be compatible with `rt-commerce/process-payment`.
*
* It is recommended to use the helpers in \rtCommerce\Payment\Abilities\ProcessPaymentAbilitySchema.
*
* @param string $ability_name The default ability name. Default: 'rt-commerce/process-payment'.
* @param mixed $previous_step_result The result of the previous step in the workflow.
*/
$ability_name = apply_filters( 'rt-commerce/payment/process-payment/ability-name', 'rt-commerce/process-payment', $previous_step_result );
$payment_status = wp_get_ability( $ability_name )->execute( $process_payment_input );
// ... rest of workflow logic untouched.
// Elsewhere, say what ability to use for processing payment.
add_filter(
'rt-commerce/payment/process-payment/ability-name',
static function ( $ability_name, $previous_step_result ): string {
if ( isset( $previous_step_result['checkout']['region'] ) ) {
return self::get_default_ability_for_region( $previous_step_result['checkout']['region'] );
}
return $ability_name;
},
10,
2
);
// Then register the appropriate ability for the region.
add_action( 'wp_abilities_api_init', static function () {
wp_register_ability(
'rt-commerce-affiliate/process-stripe-payment',
[
// ... the other props.
'input_schema' => self::assert_compatible_schema( \rtCommerce\Payment\Abilities\ProcessPaymentAbilitySchema::input_schema(), self::input_schema() ),
'output_schema' => \rtCommerce\Payment\Abilities\ProcessPaymentAbilitySchema::output_schema(),
'execute_callback' => static function ( array $input ): array|\WP_Error {
// Or whatever payment processing logic you need for Stripe.
$charge = self::process_stripe_payment( $input );
if ( is_wp_error( $charge ) ) {
return $charge;
}
// Return something compatible with the output schema.
return self::assert_compatible_output( \rtCommerce\Payment\Abilities\ProcessPaymentAbilitySchema::output_schema(),
$charge
);
},
]
);
} );
(To be clear, those assert_* calls are pure theorycraft, and most implementations can just return an input they know to be compatible with the schema per manual inspection or integration tests if needed. The whole point of abilities is that you should be able to trust the schemas won’t break on you.)
Extending Abilities
A more common pattern in e-commerce is to support multiple payment providers at a time. In this scenario, we’re not replacing rt-commerce/process-payment, but extending it.
Say a PayPal add-on wants to offer PayPal support alongside the existing payment types rt-commerce/process-payment already supports. We can make our changes additively with the wp_register_ability_args filter.
add_filter(
'wp_register_ability_args',
static function ( $args, $name ) {
if ( 'rt-commerce/process-payment' !== $name ) {
return $args;
}
// Each payment method is its own `oneOf` branch, so we can add ours without touching the others.
$args['input_schema']['properties']['payment']['oneOf'][] = [
'title' => 'PayPal',
'type' => 'object',
'properties' => [
'method' => [ 'type' => 'string', 'enum' => [ 'paypal' ] ],
'paypal_order_id' => [
'type' => 'string',
'description' => __( 'The PayPal order to capture.', 'rt-commerce-paypal' ),
],
],
'required' => [ 'method', 'paypal_order_id' ],
'additionalProperties' => false,
];
// Keep the output optional for backward/cross compatibility with other payment types.
$args['output_schema']['properties']['paypal'] = [
'type' => [ 'object', 'null' ],
'properties' => [
'capture_id' => [ 'type' => 'string' ],
// Other fields here...
],
'additionalProperties' => false,
];
// Wrap the existing execute callback in ours.
$original_callback = $args['execute_callback'];
$args['execute_callback'] = static function ( $input ) use ( $original_callback ) {
if ( 'paypal' !== $input['payment']['method'] ) {
return $original_callback( $input );
}
// Handle PayPal payment here.
// You would typically call your PayPal SDK or API to capture the payment.
$paypal_capture = self::process_paypal_payment( $input );
if ( is_wp_error( $paypal_capture ) ) {
return $paypal_capture;
}
return self::assert_compatible_output( \rtCommerce\Payment\Abilities\ProcessPaymentAbilitySchema::output_schema(),
[
'paypal' => [
'capture_id' => $paypal_capture['id'],
],
]
// ... other output fields we need to guarantee.
);
};
return $args;
},
10,
2
);
By following Part 3’s rules for future compatibility, we ensure that our PayPal integration stays compatible with the Ability it’s extending. In a real plugin ecosystem situation, you would likely want to abstract the extension logic into a dedicated class that validates and enforces these patterns and not leave it for all extension builders to handle individually.
Domain-Driven Boundaries
So far, we’ve mostly treated Abilities as the contract between your code and someone else’s, but in a large codebase, the biggest consumer of Abilities is usually your own code. We can use Abilities as a low-effort way to enforce Domain-Driven Design, by deciding where your boundaries go, and then ensuring that all access to a particular domain happens through its Abilities, rather than directly reaching into the internal implementation of that domain.
In other words, just as Abilities can serve as the public API for downstream consumers, they can also serve as the public API for a domain. If the Order domain needs to charge a card, it should call rt-commerce/process-payment rather than whatever the payment domain uses internally.
Abilities also allow us to identify good candidates for domain boundaries. If we sort the steps from our checkout workflow by the domain they belong to, we get:
| Ability | Domain |
|---|---|
| rt-commerce/get-customer | Customer |
| rt-commerce/validate-cart-items | Catalog |
| rt-commerce/process-payment | Payment |
| rt-commerce/place-order | Order |
| rt-commerce/confirm-payment | Payment |
| rt-commerce/award-loyalty-points | Loyalty |
| rt-commerce/send-order-confirmation | Notification |
| rt-commerce/send-to-fulfillment | Fulfillment |
If specific code logic only makes sense for one flow – e.g. ERP imports skipping a confirmation email, it belongs with the caller in the preexisting domain. If, however, multiple flows need it, we can isolate it into a new domain, and enforce access via an Ability.
That said, not every piece of logic needs to be exposed as an Ability, and there are some nuances to consider when using an Ability as a domain boundary.
Sharing Schemas between Domains
For domains to interact safely, they need to agree on the shape of that data, and duplicating schema definitions across domains leads to drift. In earlier examples we used a helper pattern like Schema::order(), which centralizes the shared dependency, but means a change in one place affects every contract that relies on it.
The way to keep that under control is to make sure each shared shape has a clear owner, usually the domain whose data it describes. For example, the Order domain owns the Order shape, and publishes its schema alongside the primary Abilities that use it.
namespace rtCommerce\Order\Abilities;
final class Order_Schema {
public const STATUS_PENDING_PAYMENT = 'pending_payment';
public const STATUS_PROCESSING = 'processing';
public const STATUS_COMPLETED = 'completed';
public const STATUS_FAILED = 'failed';
// An order, as Abilities return it.
public static function order(): array {
return [
'type' => 'object',
'properties' => [
'id' => [ 'type' => 'integer' ],
'status' => self::status(),
'customer' => Customer_Schema::customer(), // Owned by Customer.
'items' => [
'type' => 'array',
'items' => self::line_item(),
],
'totals' => self::totals(),
'shipping_address' => [ 'oneOf' => [ Schema::address(), [ 'type' => 'null' ] ] ], // Shared by every domain.
],
'required' => [ 'id', 'status', 'customer', 'items', 'totals', 'shipping_address' ],
'additionalProperties' => false,
];
}
// A pointer to an existing order, for Abilities that take one as input.
public static function order_ref(): array {
return [
'type' => 'object',
'properties' => [ 'id' => [ 'type' => 'integer', 'minimum' => 1 ] ],
'required' => [ 'id' ],
'additionalProperties' => false,
];
}
// The possible statuses for an order.
public static function status(): array {
return [
'type' => 'string',
'enum' => [ self::STATUS_PENDING_PAYMENT, self::STATUS_PROCESSING, self::STATUS_COMPLETED, self::STATUS_FAILED ],
];
}
// The totals for an order.
public static function totals(): array {
return [
'type' => 'object',
'properties' => [
'subtotal' => Schema::money(),
'discount' => Schema::money(),
'tax' => Schema::money(),
'total' => Schema::money(),
],
'required' => [ 'subtotal', 'discount', 'tax', 'total' ],
'additionalProperties' => false,
];
}
}
You’ll notice we split the shape of order() into several smaller methods, allowing for better reuse and composability elsewhere. Similarly, an order_ref() that is used downstream by other Abilities to reference an order is owned here too, even though it’s not strictly part of the main order shape.
If another domain needs more than the owner’s shape provides, it should add its own fields instead of changing the existing ones. For example, if Fulfillment needs delivery notes, they belong in Fulfillment’s own input, alongside the address, rather than inside the Address schema that the other domains also rely on:
// rt-commerce/send-to-fulfillment
'input_schema' => [
'type' => 'object',
'properties' => [
'order' => \rtCommerce\Order\Abilities\Order_Schema::order_ref(),
'address' => \rtCommerce\Schema::address(),
'delivery_notes' => [ 'type' => 'string' ],
],
'required' => [ 'order', 'address' ],
'additionalProperties' => false,
],
Generic shapes that don’t belong to any one domain, like an address or a monetary amount, can live in a small shared namespace that every domain depends on. Since changing one of those affects every Ability at once, they should only be added intentionally and additively.
Extending another Domain’s Abilities
Above, our PayPal add-on used wp_register_ability_args to modify process-payment from outside the Payment domain – and the plugin entirely. That’s great for extensibility, but it means that the Payment domain doesn’t control its own contract, and a different domain that narrows the input or fails to handle the original callback path correctly can break every other caller without our domain ever knowing.
If a domain’s Abilities are meant to be extended, the domain should provide its own explicit extension point, so it can control how the contract evolves. For example, instead of filtering the registration args directly, the domain can collect the available payment methods and build the schema and dispatch logic itself:
// Process_Payment_Schema
public static function payment_schema(): array {
$branches = [];
/**
* Filters the payment methods `rt-commerce/process-payment` accepts.
*
* @param array<string, class-string<Payment_Method>> $methods Payment method handlers, keyed by their `method` value.
*/
$methods = apply_filters( 'rt_commerce/payment/methods', [ 'card' => Card_Payment::class ] );
foreach ( $methods as $method => $handler ) {
if ( ! is_subclass_of( $handler, Payment_Method::class ) ) {
throw new \InvalidArgumentException( sprintf( '%s must implement Payment_Method.', $handler ) );
}
// Each Payment_Method has its own schema, but Process_Payment_Schema decides how to identify the branch and enforce strictness.
$branch = $handler::payment_schema();
$branch['properties']['method'] = [ 'type' => 'string', 'enum' => [ $method ] ];
$branch['required'] = array_values( array_unique( [ 'method', ...( $branch['required'] ?? [] ) ] ) );
$branch['additionalProperties'] = false;
$branches[] = $branch;
}
return $branches;
}
// Then in our actualized schema:
public static function input_schema(): array {
return [
'type' => 'object',
'properties' => [
'payment' => [ 'oneOf' => self::payment_schema() ],
'items' => self::items_schema(),
],
'required' => [ 'payment', 'items' ],
'additionalProperties' => false,
];
}
Our input schema now dynamically incorporates the available payment methods, while the payment_schema method ensures each branch is properly structured and validated.
Performance
So far, we’ve treated the cost of calling an Ability as negligible, and in many cases it is. The more complex our Abilities become and the more Abilities we compose together, the more their overhead starts to matter. Abilities aren’t lazy-loaded, so the first time a request touches the registry, every Ability on the site is registered with its schemas built and translated, whether or not the request uses any of them. Each call to ::execute() validates the entire input and output – sometimes repeatedly for the same data – and since there’s no way to request only part of an output, callers pay for every field whether they use it or not.
How much the cost matters depends on how an Ability is used. An Ability called once per item in a loop pays the per-call overhead for each item, and when you start dealing with an ERP import of two million orders or an order history page loading hundreds of orders at once, it can really add up.
In this section, let’s look at a few patterns for mitigating the performance overhead of Abilities.
Observability and tracing
The first step to solving any problem is understanding it, and we can use existing Ability hooks to instrument and trace the execution of Abilities. By logging execution time, we can identify bottlenecks and optimize accordingly:
add_action( 'wp_before_execute_ability', static function ( string $ability_name ): void {
// Or whatever you're already using: Query Monitor, OpenTelemetry, New Relic, etc.
\rtCommerce\Telemetry::start( $ability_name );
} );
add_action( 'wp_after_execute_ability', static function ( string $ability_name ): void {
\rtCommerce\Telemetry::end( $ability_name );
} );
If an Ability calls other Abilities it’s useful to group those calls under whatever kicked off the original execution. For example, the workflow ID from our orchestration loop can be used as a trace ID to correlate all related Ability executions.
Batching and N+1 calls
One of the most common performance pitfalls is the N+1 query problem, where an Ability repeatedly calls another Ability in a loop, resulting in many redundant executions. An Order History page that calls rt-commerce/get-order for each order pays the validation and permission overhead on top of the queries called by each execution, as well as re-running any hook callbacks multiple times.
Instead of wrapping the loop in a /get-orders ability, structure your Abilities to fetch multiple items at once. This reduces redundant executions and allows for more efficient permission checks and data retrieval:
// rt-commerce/get-orders
'permission_callback' => static function ( ?array $input = null ): bool {
if ( ! $input ) {
return current_user_can( 'view_order' );
}
return self::can_view_all( $input['user_id'], array_column( $input['orders'] ?? [], 'id' ) );
},
'execute_callback' => static function ( array $input ): array {
$ids = array_column( $input['orders'], 'id' );
$loaded = Internal\Order_Repository::get_many( $ids );
$result = [ 'orders' => [], 'errors' => [] ];
foreach ( $ids as $i => $id ) {
if ( ! isset( $loaded[ $id ] ) ) {
$result['orders'][] = null;
$result['errors'][] = [
'code' => 'order_not_found',
'message' => sprintf( __( 'Order %d does not exist.', 'rt-commerce' ), $id ),
'path' => [ 'orders', $i ],
'data' => [ 'id' => $id ],
];
continue;
}
$result['orders'][] = $loaded[ $id ]->to_array();
}
return $result;
},
To fetch a single order you can pass a single-item array to the Ability, there’s no need to register a singular /get-order as well. Dropping the per-item Ability also means you don’t need to maintain separate schemas and permission logic, nor worry about keeping them in sync.
Over-fetching and Output Filtering
A robust Ability schema provides all the output fields that might be needed by consumers, but that doesn’t mean every consumer needs all the fields all of the time. An Order History page only needs the ID, status, and total, while the order detail page will have line items, customer information, shipping details, and who knows what else. Unlike GraphQL or the WordPress REST API, the Abilities API has no way for a caller to choose which fields to include in the response, but we can add that to the input schema ourselves:
// rt-commerce/get-orders
'input_schema' => [
// ...
'fields' => [
'type' => 'array',
'items' => [
'type' => 'string',
// Building the `enum` directly from the output schema keeps it in sync with the output shape.
'enum' => array_keys( Order_Schema::order()['properties'] ),
],
'description' => __( 'The order fields to return. Defaults to `id`.', 'rt-commerce' ),
],
]
The execute_callback can then use fields to decide not just what fields to return, but to fetch:
'execute_callback' => static function ( array $input ): array {
// Required fields are always returned, whether or not they were requested.
$fields = array_unique( [
'id',
...( $input['fields'] ?? [] )
] );
$ids = array_column( $input['orders'], 'id' );
// Internally, we only fetch the fields that were requested.
$loaded = Internal\Order_Repository::get_many( $ids, $fields );
// Only fetch customer information if requested, for every order at once.
$customers = in_array( 'customer', $fields, true )
? Internal\Customer_Repository::get_many( array_column( $loaded, 'customer_id' ) )
: [];
// Filter out return values that weren't requested.
$order = array_intersect_key( $loaded[ $id ]->to_array(), array_flip( $fields ) );
if ( $customers ) {
$order['customer'] = $customers[ $loaded[ $id ]->customer_id ] ?? null;
}
$result['orders'][] = $order;
// ...
}
Keep in mind that any fields you allow your consumers to skip should be marked optional in your output schema. Required fields should always be included in the response, even if not requested by the caller.
Pagination
Now we’re filtering the data in each order, but we still need to handle how many orders come back. An Order History page that passes only a user_id gets every order that customer has ever placed, all loaded and validated in a single request. Instead, we can cap the number of orders per call and let the caller request them a page at a time, the same way WP_Query does with paged and posts_per_page:
// Pagination args added to the input schema:
'pagination' => [
'type' => 'object',
'properties' => [
'page' => [ 'type' => 'integer', 'minimum' => 1, 'default' => 1 ],
'per_page' => [ 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20 ],
// Opt-in to match WP_Query's `no_found_rows`.
'include_total' => [ 'type' => 'boolean', 'default' => false ],
],
'additionalProperties' => false,
],
// Pagination info added to the output schema:
'page_info' => [
'type' => 'object',
'properties' => [
'has_next_page' => [ 'type' => 'boolean' ],
'total' => [ 'type' => [ 'integer', 'null' ] ], // Null unless `include_total` is set.
],
'required' => [ 'has_next_page', 'total' ],
'additionalProperties' => false,
]
Here, the input schema allows the caller to provide which subset of orders they want, while the output schema lets the caller know where their slice of data fits within the overall set of orders.
In frequently updated sets, page-based pagination breaks down when working across multiple requests, like background job processing or frontend lazy-loading. If a new order is placed while it’s running, the existing order placement shifts to cause an off-by-one error in the retrieved pages, and page 5 now includes an order that was previously on page 4. Cursor-based pagination solves this by using a stable reference point for each order, such as a timestamp or a unique ID, to determine the starting point for the next page of results.
// Added to `pagination` in the input, as an alternative to `page`.
'after' => [
'type' => [ 'string', 'null' ],
'description' => __( 'Return orders after this cursor, from a previous page\'s `page_info.end_cursor`.', 'rt-commerce' ),
],
// Added to `page_info` in the output.
'end_cursor' => [ 'type' => [ 'string', 'null' ] ],
WP_Query doesn’t natively support cursor-based pagination, so if you go down this path you will need to implement the logic for handling the after cursor and generating the end_cursor yourself, typically by ordering by a stable field like ID or date, and using date_query or a posts_where filter to only fetch results past the cursor.
Caching results
Caching can save the work inside an execute_callback, reducing the need to repeatedly fetch and process the same data for identical requests. This can be particularly useful for expensive queries or computations that are unlikely to change frequently.
Since there are not currently filters to early-return cached results, you can use wp_register_ability_args to wrap an execute_callback. Here’s a basic example that uses a custom meta property to opt an Ability into caching:
add_filter( 'wp_register_ability_args', static function ( $args, $name ): array {
// Our custom meta key.
$cache_group = $args['meta']['rt_commerce']['cache_group'] ?? null;
// Only cache read-only Abilities with our custom cache group.
if ( ! $cache_group || true !== ( $args['meta']['annotations']['readonly'] ?? false ) ) {
return $args;
}
// Wrap the original execute callback with caching logic.
$callback = $args['execute_callback'];
$args['execute_callback'] = static function ( $input = null ) use ( $name, $cache_group, $callback ) {
// Generate a cache key based on the ability name, input, and last cache change.
$key = md5( wp_json_encode( [ $name, $input, wp_cache_get_last_changed( $cache_group ) ] ) );
// Attempt to retrieve the cached result.
$cached = wp_cache_get( $key, $cache_group );
if ( false !== $cached ) {
return $cached;
}
// If there's no cached result, run normally.
$result = $callback( $input );
// Errors are often temporary, so we don't cache them.
if ( ! is_wp_error( $result ) ) {
wp_cache_set( $key, $result, $cache_group, HOUR_IN_SECONDS );
}
return $result;
};
return $args;
}, 10, 2 );
Invalidation works the same way it does for WordPress’s own query caches: our plugin logic can call wp_cache_set_last_changed('rt-commerce-orders') whenever an order changes to invalidate the cached results. Since we only wrap the execute_callback, the permission callback still runs on every call, including cache hits. If the output itself can vary by the user calling the ability, we should also include the user ID in the cache key, instead of relying on the $input alone.
Wrapping up
In this article, we explored advanced techniques for using WordPress Abilities effectively. We composed them into workflows, aggregated and recovered from errors partway through a chain, and persisted state so an Ability chain can pause for an external action or async job and pick up where it left off. We extended existing Abilities and swapped them with others, used them as a public API without our own codebase modules, and looked at how to keep them performant with tracing, batching, field filtering, pagination, and caching.
The Abilities API is still new, and some of the manual work should get easier as it evolves, alongside new features and use cases. If you run into a pattern we didn’t cover, or a limitation that made one of these harder than it should be, WordPress Trac and the Core AI team are good places to report it and discuss potential improvements.
Thanks for reading along, and happy, predictable coding!







