Custom WooCommerce REST API endpoint

/**
 * Adds public custom WooCommerce REST API endpoint.
 *
 * https://example.com/wp-json/wc/v3/wpcodebook?param1=test
 *
 * @see https://wpcodebook.com/custom-woocommerce-rest-api-endpoint/
 * @see https://developer.wordpress.org/reference/hooks/rest_api_init/
 * @see https://developer.wordpress.org/reference/functions/register_rest_route/
 * @see https://woocommerce.github.io/woocommerce-rest-api-docs/
 * @see https://stackoverflow.com/questions/34963720/woocommerce-api-v3-custom-endpoint
 */
add_action( 'rest_api_init', function () {
	register_rest_route( 'wc/v3', '/wpcodebook', array(
		'methods'             => 'GET',
		'permission_callback' => '__return_true',
		'callback'            => function ( $request ) {
			return array( 'request_params' => $request->get_params() );
		},
	) );
} );

JSON output:

{
	request_params: {
		param1: "test"
	}
}

Leave a Comment