Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce Rest API Issue on local server

I am working on a plugin to interact with a WooCommerce store and the problem is that the plugin and the store are on the same WordPress installation (same server and domain) and the WooCommerce Rest API didn't work. I have already asked this question:

WooCommerce API Issue with Authentication Consumer Key is missing

My question: Is there a way to interact with WooCommerce directly without the Rest API, specially if my plugin and WooCommerce store are on the same server?

like image 756
Waxren Avatar asked Sep 03 '25 02:09

Waxren


1 Answers

I finally found the solution, in order to access the WooCommerce API directly without using the REST API I first found great code on this link:

https://wordpress.org/support/topic/programming-question-memory-leak-when-accessing-products

And using this great link documentation

https://web.archive.org/web/20160616131215/http://woocommerce.wp-a2z.org/oik_file/includesapiv2class-wc-api-orders-php/

Then by navigating in WooCommerce Source code in the plugins folder under plugins/woocommerce/includes/api

I succeeded to access WooCommerce, here is a simple example to get products of a category and using page number:

//you need to sign in with wordpress admin account to access WooCommerce data
function setupWooCommerce() {
    $wooCommercePath = realpath(WP_PLUGIN_DIR . '/woocommerce/woocommerce.php');
    require_once $wooCommercePath;

    WC()->api->includes();
    WC()->api->register_resources(new WC_API_Server( '/' ));

    $credentials = [
        'user_login' => 'username',
        'user_password' => 'password'
    ];
    $user = wp_signon($credentials, false);
    wp_set_current_user($user->ID);
}

function getProducts($category, $pageNumber) {
    setupWooCommerce();
    $products = NULL;
    try {
        $api = WC()->api->WC_API_Products;
        $products = $api->get_products(null, null, array('category' => $category), $pageNumber);
    } catch (Exception $e) {
        error_log("Caught $e");
    }
    return $products;
}
like image 59
Waxren Avatar answered Sep 05 '25 00:09

Waxren