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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With