WooCommerce API Custom Endpoint




WooCommerce is great. But when it comes to API, it requires a little work to do some modifications. Let us take an example of custom endpoints. To make your own woocommerce api endpoint to return custom content, follow this tutorial.
api custom endpoint

  1. Create your own plugin. WordPress Docs will help you achieve this
  2. In plugins main file add the following code: (Don’t forget opening php tag.)
    add_action( 'woocommerce_api_loaded', function(){
    	include_once( 'class-wc-api-custom.php' );
    });
    add_filter( 'woocommerce_api_classes', function( $classes ){
    	$classes[] = 'WC_API_Custom';
    	return $classes;
    });
  3. Create a file class-wc-api-custom.php in plugin’s root directory and add the following code in that file:
    <?php
    class WC_API_Custom extends WC_API_Resource {
    	protected $base = '/custom';
    
    	public function register_routes( $routes ) {
    		$routes[ $this->base ] = array(
    			array( array( $this, 'get_custom' ), WC_API_Server::READABLE )
    		);
    
    		return $routes;
    	}
    	
    	public function get_custom() {
    		return array( 'custom' => 'Data' );
    	}
    }

Now your custom endpoint is wc-api/v3/custom which will return content from get_custom function.

One comment

Leave a Reply


Your email address will not be published. Required fields are marked *