A few years ago I have written a post on “How to create custom endpoint in WooCommerce API“. That was I think for v3 of older WooCommerce. After that, I did not get much time to work on WooCommerce products. But since then I was getting some queries on how to achieve the same for the latest version of Woo. So thought of doing some research. However when I saw their documentation today, it still says version 3, but everything is changed. Ironic.
Anyways, I quickly set up a local dev environment and tried to create a custom endpoint today. It’s much easier now. Since WordPress integrated REST API in it’s core, we can just register a route which would simply have wc/v3
as the $namespace
, custom
as the $route
, and callback in the $args. This will have a custom WC Endpoint!
Code is as follows:
function get_custom( $data ) {
return array( 'custom' => 'Data' );
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wc/v3', 'custom', array(
'methods' => 'GET',
'callback' => 'get_custom',
));
})
You can add the above code in your theme or custom plugin.
However, if you want to extend WooCommerce REST Controllers, you can use woocommerce_rest_api_get_rest_namespaces
filter.
1. Create a Custom REST Controller Class.
class WC_REST_Custom_Controller {
/**
* You can extend this class with
* WP_REST_Controller / WC_REST_Controller / WC_REST_Products_V2_Controller / WC_REST_CRUD_Controller etc.
* Found in packages/woocommerce-rest-api/src/Controllers/
*/
protected $namespace = 'wc/v3';
protected $rest_base = 'custom';
public function get_custom( $data ) {
return array( 'custom' => 'Data' );
}
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
'methods' => 'GET',
'callback' => array( $this, 'get_custom' ),
)
);
}
}
2. Then register this custom controller in the wc/v3
namespace with the help of hook as follows:
add_filter( 'woocommerce_rest_api_get_rest_namespaces', 'woo_custom_api' );
function woo_custom_api( $controllers ) {
$controllers['wc/v3']['custom'] = 'WC_REST_Custom_Controller';
return $controllers;
}
Now navigate to your-site/wp-json/wc/v3/custom
and test your custom endpoint. It should return {"custom":"Data"}
or whatever you return in WC_REST_Custom_Controller
‘s get_custom
method.
1 comment
Brilliant! I’ve been combing documentation to be able to build a custom callback. Have written dozens of lines of code to test various scenarios. This example makes everything clear and suddenly it seems so simple!