Skip to content

Instantly share code, notes, and snippets.

@mklasen
Last active September 27, 2019 08:27
Show Gist options
  • Save mklasen/5c40d4d92590aeff94061c218be4cb95 to your computer and use it in GitHub Desktop.
Save mklasen/5c40d4d92590aeff94061c218be4cb95 to your computer and use it in GitHub Desktop.
Extend the Woocommerce REST API (with authentication)
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class Sample_Extend_Endpoint extends WC_REST_Controller {
protected $namespace = 'wc/v3';
protected $rest_base = 'sample_endpoint';
public function register_routes() {
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'callback_action' ),
'permission_callback' => array( $this, 'callback_action_permissions_check' ),
'args' => $this->get_collection_params(),
) );
}
public function callback_action($request) {
return json_encode($request->get_params());
}
public function callback_action_permissions_check( $request ) {
$id = (int) $request['id'];
if ( ! wc_rest_check_user_permissions( 'edit', $id ) ) {
return new WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you cannot edit this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
}
return true;
}
}
<?php
class Sample_Plugin {
public function __construct() {
$this->init();
}
public function init() {
add_filter( 'rest_api_init', array( $this, 'init_extend_endpoint' ) );
}
public function init_extend_endpoint() {
include_once get_stylesheet_directory() . '/class-extend-endpoint.php';
$save_template = new Sample_Extend_Endpoint();
$save_template->register_routes();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment