Reputation: 2172
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?
Upvotes: 4
Views: 1612
Reputation: 2172
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
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;
}
Upvotes: 2
Reputation: 454
You can use wp rest api. below example show you last 12 orders:
$request = new WP_REST_Request('GET', '/wc/v3/orders/');
$request->set_query_params(['per_page' => 12]);
$response = rest_do_request($request);
$server = rest_get_server();
$data = $server->response_to_data($response, false);
$json = wp_json_encode($data);
sources: https://wpscholar.com/blog/internal-wp-rest-api-calls/ , https://developer.wordpress.org/rest-api/reference/posts/#list-posts
Upvotes: 0