/   /   /  WooCommerce Add custom api route

Note:

For more extensions and themes visit our store

WooCommerce Add custom api route


In WooCommerce the rest api is used to get data from orders , products , customers..
but how you can customize or add add other api route  to get (fields and value) , ok it's exist many techniques
first work directly on the core for example inside :

woocommerce/includes/class-wc-api.php in fuction includes or handle_v1_rest_api_request() or handle_v2_rest_api_request() :

add :

  1.  
  2. include_once( 'api/class-wc-api-customs.php' );
  3.  

and you will find apply_filters add you custom class to filters :

  1.  
  2. $api_classes = apply_filters( 'woocommerce_api_classes',
  3. 'WC_API_Customers',
  4. 'WC_API_Orders',
  5. 'WC_API_Customs',
  6. 'WC_API_Products',
  7. 'WC_API_Coupons',
  8. 'WC_API_Reports',
  9. )
  10. );
  11.  

Now you should add the class class-wc-api-customs.php extends WC_API_Resource the content is :

  1.  
  2. <?php
  3. if ( ! defined( 'ABSPATH' ) ) {
  4. exit; // Exit if accessed directly
  5. }
  6. class WC_API_ Customs extends WC_API_Resource {
  7. /** @var string $base the route base */
  8. protected $base = '/customs';
  9. /** @var string $post_type the custom post type */
  10. protected $post_type = 'shop_cart';
  11. /**
  12. * @return array
  13. */
  14. public function register_routes( $routes ) {
  15. # GET|POST /carts
  16. $routes[ $this->base ] = array(
  17. array( array( $this, 'get_count_customs' ), WC_API_Server::READABLE ),
  18. );
  19. return $routes;
  20. }
  21. public function get_count_customs( $status = null, $filter = array() ) {
  22. $count_customs = 7;
  23. return apply_filters('carts_count',$count_customs);
  24. }
  25. }
  26.  

Conclusion  : we have declared our custom route inside register_routes with name get_count_customs and we created function for done something .
Now you can use by example Api v2 or 3 for call :
wc-api/v3/get_count_customs
2 : plugin :

inside woocommerce-ac.php add :

  1.  
  2. add_action('woocommerce_api_loaded', 'wpc_register_wp_api_endpoints');
  3. function wpc_register_wp_api_endpoints() {
  4. include_once( 'woo-includes/api/v2/class-wc-api-carts.php' );
  5. add_filter('woocommerce_api_classes', 'filter_woocommerce_api_classes', 10, 1);
  6. }
  7. function filter_woocommerce_api_classes($array) {
  8. $cart = array(
  9. 'WC_API_Carts',
  10. );
  11. return array_merge($array, $cart);
  12. }
  13.  

and inside woo-includes/api/v2 add class-wc-api-customs.php add you code
that is done

Comments

IBNAB is a company made of a group of professionals whose work is providing secure open source solutions. Our company strives for reaching magnificent results with each experience and provides professional open source solutions that cover every part of the business process.