Add a Custom URL to WooCommerce with the woocommerce_api_(action) Hook

The woocommerce_api_(action) hook in WooCommerce lets a plugin attach a custom callback to a URL. When that URL is visited, the function or method bound to the callback runs. This API is used frequently in WooCommerce payment gateways, but it is also useful whenever WooCommerce needs to receive data back from a third-party service. For more background, refer to the WC_API class documentation.

What the callback URL looks like

Before WooCommerce 2.0, a custom callback URL was usually accessed in a format like the following:

http://yoursite.com/?wc-api=CALLBACK

After WooCommerce 2.0, in addition to the parameter-based URL above, we can also access the callback through a cleaner static-style URL:

http://yoursite.com/wc-api/CALLBACK/

Add a custom URL

We can register a custom callback URL with code like the following:

add_action( 'woocommerce_api_callback', 'callback_handler' );

Notice the string callback inside the hook name woocommerce_api_callback. That piece is the unique name of our custom callback, and it becomes part of the callback URL. We also need that same name later when we want to retrieve the callback URL programmatically.

After the callback logic has finished running, WooCommerce exits the request. If needed, we can still redirect the user to another URL before exiting.

Get the custom callback URL

WooCommerce provides a method on the WC() instance that returns the full URL for a custom callback.

WC()->api_request_url( 'wc_ezship_send_order' )

When building a WooCommerce payment gateway or another third-party integration, that method is the easiest way to generate the custom callback URL you need.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *