Skip to content

Instantly share code, notes, and snippets.

@Skatox
Created November 16, 2015 21:19
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Skatox/5f1040ee352cee455cca to your computer and use it in GitHub Desktop.
Save Skatox/5f1040ee352cee455cca to your computer and use it in GitHub Desktop.
Woocommerce API REST custom path
<?php
/**
* Custom API REST path class
*
* @package MyPlugin
* @author Skatox
*/
class WC_API_Custom extends WC_API_Resource
{
const PATH = '/custom';
/**
* Function to define each of the custom path
*/
public function register_routes($routes)
{
//GET Request
$routes[self::PATH . '/orders'] = array(
array(array($this, 'listShippingOrders'), WC_API_Server::READABLE),
);
//POST Request
$routes[self::PATH . '/orders/(?P<order_id>\d+)/fulfillments.json'] = array(
array(array($this, 'createItem'), WC_API_Server::CREATABLE | WC_API_Server::ACCEPT_DATA),
);
//PUT Request
$routes[self::PATH . '/variants/(?P<id>\d+).json'] = array(
array(array($this, 'updateItem'), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA),
);
return $routes;
}
public function listShippingOrders($fields = null, $filter = array(), $status = null, $page = 1)
{
$wcApiOrders = new WC_API_Orders($this->server);
$orders = $wcApiOrders->get_orders($fields, $filter, $status, $page);
//Removes orders without shipping methods
foreach ($orders['orders'] as $key => $oreder)
{
if (empty($oreder['shipping_methods'])) {
unset($oreders['orders'][$key]);
continue;
}
}
return $order;
}
public function createItem($order_id, $data)
{
//Do insert proccess and then return the response array
}
public function updateItem($id, $data)
{
//Do update proccess and then return the response array
}
}
<?php
/**
* Plugin Name: Woocommerce custom path example
* Description: Custom API calls plugin
* Version: 1.0
* Author: Miguel Useche
* Author URI: http://migueluseche.com
* License: GPL 3.0
*
* @package MyPlugin
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if (!class_exists('WD_API_LOADER')) {
/**
* Main plugin class
*
* @package MyPlugin
* @author Skatox
*/
class WD_API_LOADER
{
public function init()
{
add_action( 'woocommerce_api_loaded', array( $this, 'load' ) );
}
public function load()
{
require_once plugin_dir_path( __FILE__ ).'wc-api-custom.php';
add_filter( 'woocommerce_api_classes', array( $this, 'register' ) );
}
public function register( $api_classes=array() )
{
array_push( $api_classes, 'WC_API_Custom' );
return $api_classes;
}
}
}
$wc_custom_api = new WD_API_LOADER();
$wc_custom_api->init();
@tchafack
Copy link

Thank you !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment