Skip to content

Instantly share code, notes, and snippets.

@bot101
Forked from Skatox/wc-api-custom.php
Created July 21, 2017 09:28
Show Gist options
  • Save bot101/694da2dc41ff50016210f8e703c700f2 to your computer and use it in GitHub Desktop.
Save bot101/694da2dc41ff50016210f8e703c700f2 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment