Skip to content

Adding Methods to the API

Jason Knight edited this page Sep 4, 2013 · 15 revisions

I am writing this page while actually adding a new feature to the API, this will be particularly in depth.

The first step is to open up classes/class-wc-json-api.php and find the function called public static function getImplementedMethods(), it will look similar to this:

<?php
public static function getImplementedMethods() {
    if (self::$implemented_methods) {
      return self::$implemented_methods;
    }
    self::$implemented_methods = array(
      'get_system_time',
      'get_products',
      'get_categories',
      'get_taxes',
      'get_shipping_methods',
      'get_payment_gateways',
      'get_tags',
      'get_products_by_tags',
      'get_customers',
      
      // Write capable methods
      
      'set_products',
      'set_categories',

    );
    return self::$implemented_methods;
  }

In this case, we will add the method "get_orders". All methods are named get|set_{resource}s. Since the API thinks ONLY IN COLLECTIONS.

We will modify it like so:

<?php
  public static function getImplementedMethods() {
    if (self::$implemented_methods) {
      return self::$implemented_methods;
    }
    self::$implemented_methods = array(
      'get_system_time',
      'get_products',
      'get_categories',
      'get_taxes',
      'get_shipping_methods',
      'get_payment_gateways',
      'get_tags',
      'get_products_by_tags',
      'get_customers',
      'get_orders', // New Method
      
      // Write capable methods
      
      'set_products',
      'set_categories',

    );
    return self::$implemented_methods;
  }

Here we have added the new method get_orders. We will need to scroll to the bottom of the file and add a method like so:

<?php
public function get_customers( $params ) {
    global $wpdb;
    $customer_ids = $wpdb->get_col("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'wp_capabilities' AND meta_value LIKE '%customer%'");
    $customers = array();
    foreach ( $customer_ids as $id ) {
      $c = WC_JSON_API_Customer::find( $id );
      $customers[] = $c->asApiArray();
    }
    $this->result->setPayload($customers);
    return $this->done();
  }

  public function get_orders( $params ) {

    return $this->done();
  }

In this case, we added get_orders right after the function get_customers. Normally, we group functions of like kind together. So new methods for customers would be inserted after get_customers and befor get_orders.

Always end the function with return $this->done(); This is a special method that takes care of preparing our results and returning them based on the configuration.

Clone this wiki locally