I had a task to create a PHP script to import simple and variable products from JSON file using the WooCommerce REST API. Thought it might be worth sharing with others because I couldn’t find much information about products import from JSON using the API.
To make it easier to understand, I created a simple JSON file with one simple product and one variable product that have two product variations. You can get all files from Github repository.
products.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
[ { "product_id": 100, "type": "simple", "name": "My product 1", "description": "My product description 1", "regular_price": 100, "manage_stock": 1, "stock": 3, "weight": 0, "has_variations": 0 }, { "product_id": 200, "type": "variable", "name": "My product 2", "description": "My product description 2", "regular_price": 0, "manage_stock": 0, "stock": 0, "weight": 0, "attribute_name": "Color", "has_variations": 1 }, { "type": "product_variation", "parent_product_id": 200, "description": "My product variation 1", "regular_price": 120, "manage_stock": 1, "stock": 5, "weight": 0, "attribute_name": "Color", "attribute_value": "red" }, { "type": "product_variation", "parent_product_id": 200, "description": "My product variation description 2", "regular_price": 180, "manage_stock": 1, "stock": 6, "weight": 0, "attribute_name": "Color", "attribute_value": "green" } ] |
Getting started
What you need to do is download a PHP wrapper for the WooCommerce REST API. You can download it using composer from https://packagist.org/packages/automattic/woocommerce If you don’t have composer yet, then you can download it from https://getcomposer.org
Setup
Setup for the new WP REST API integration (WooCommerce 2.6 or later):
1 2 3 4 5 6 7 8 9 10 11 12 13 |
require __DIR__ . '/vendor/autoload.php'; use Automattic\WooCommerce\Client; $woocommerce = new Client( 'http://example.com', 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', [ 'wp_api' => true, 'version' => 'wc/v2', ] ); |
1. Parse JSON
Convert JSON string to PHP array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/** * Parse JSON file. * * @param string $file * @return array */ function parse_json( $file ) { $json = json_decode( file_get_contents( $file ), true ); if ( is_array( $json ) && !empty( $json ) ) : return $json; else : die( 'An error occurred while parsing ' . $file . ' file.' ); endif; } |
2. Get all product attributes from JSON
We need to get all product attributes names and values from JSON file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * Get attributes and terms from JSON. * Used to import product attributes. * * @param array $json * @return array */ function get_attributes_from_json( $json ) { $product_attributes = array(); foreach( $json as $key => $pre_product ) : if ( !empty( $pre_product['attribute_name'] ) && !empty( $pre_product['attribute_value'] ) ) : $product_attributes[$pre_product['attribute_name']]['terms'][] = $pre_product['attribute_value']; endif; endforeach; return $product_attributes; } |
3. Get products and variations from JSON for importing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
/** * Get products from JSON and make them ready to import according WooCommerce API properties. * * @param array $json * @param array $added_attributes * @return array */ function get_products_and_variations_from_json( $json, $added_attributes ) { $product = array(); $product_variations = array(); foreach ( $json as $key => $pre_product ) : if ( $pre_product['type'] == 'simple' ) : $product[$key]['_product_id'] = (string) $pre_product['product_id']; $product[$key]['name'] = (string) $pre_product['name']; $product[$key]['description'] = (string) $pre_product['description']; $product[$key]['regular_price'] = (string) $pre_product['regular_price']; // Stock $product[$key]['manage_stock'] = (bool) $pre_product['manage_stock']; if ( $pre_product['stock'] > 0 ) : $product[$key]['in_stock'] = (bool) true; $product[$key]['stock_quantity'] = (int) $pre_product['stock']; else : $product[$key]['in_stock'] = (bool) false; $product[$key]['stock_quantity'] = (int) 0; endif; elseif ( $pre_product['type'] == 'variable' ) : $product[$key]['_product_id'] = (string) $pre_product['product_id']; $product[$key]['type'] = 'variable'; $product[$key]['name'] = (string) $pre_product['name']; $product[$key]['description'] = (string) $pre_product['description']; $product[$key]['regular_price'] = (string) $pre_product['regular_price']; // Stock $product[$key]['manage_stock'] = (bool) $pre_product['manage_stock']; if ( $pre_product['stock'] > 0 ) : $product[$key]['in_stock'] = (bool) true; $product[$key]['stock_quantity'] = (int) $pre_product['stock']; else : $product[$key]['in_stock'] = (bool) false; $product[$key]['stock_quantity'] = (int) 0; endif; $attribute_name = $pre_product['attribute_name']; $product[$key]['attributes'][] = array( 'id' => (int) $added_attributes[$attribute_name]['id'], 'name' => (string) $attribute_name, 'position' => (int) 0, 'visible' => true, 'variation' => true, 'options' => $added_attributes[$attribute_name]['terms'] ); elseif ( $pre_product['type'] == 'product_variation' ) : $product_variations[$key]['_parent_product_id'] = (string) $pre_product['parent_product_id']; $product_variations[$key]['description'] = (string) $pre_product['description']; $product_variations[$key]['regular_price'] = (string) $pre_product['regular_price']; // Stock $product_variations[$key]['manage_stock'] = (bool) $pre_product['manage_stock']; if ( $pre_product['stock'] > 0 ) : $product_variations[$key]['in_stock'] = (bool) true; $product_variations[$key]['stock_quantity'] = (int) $pre_product['stock']; else : $product_variations[$key]['in_stock'] = (bool) false; $product_variations[$key]['stock_quantity'] = (int) 0; endif; $attribute_name = $pre_product['attribute_name']; $attribute_value = $pre_product['attribute_value']; $product_variations[$key]['attributes'][] = array( 'id' => (int) $added_attributes[$attribute_name]['id'], 'name' => (string) $attribute_name, 'option' => (string) $attribute_value ); endif; endforeach; $data['products'] = $product; $data['product_variations'] = $product_variations; return $data; } |
4. Merge products and product variations
Used to loop through products, then loop through product variations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * Merge products and variations together. * Used to loop through products, then loop through product variations. * * @param array $product_data * @param array $product_variations_data * @return array */ function merge_products_and_variations( $product_data = array(), $product_variations_data = array() ) { foreach ( $product_data as $k => $product ) : foreach ( $product_variations_data as $k2 => $product_variation ) : if ( $product_variation['_parent_product_id'] == $product['_product_id'] ) : // Unset merge key. Don't need it anymore unset($product_variation['_parent_product_id']); $product_data[$k]['variations'][] = $product_variation; endif; endforeach; // Unset merge key. Don't need it anymore unset($product_data[$k]['_product_id']); endforeach; return $product_data; } |
5. A simple function to print status message
1 2 3 4 5 6 7 8 9 |
/** * Print status message. * * @param string $message * @return string */ function status_message( $message ) { echo $message . "\r\n"; } |
Import products to WooCommerce using the API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
try { $json = parse_json( 'products.json' ); // Import Attributes foreach ( get_attributes_from_json( $json ) as $product_attribute_name => $product_attribute ) : $attribute_data = array( 'name' => $product_attribute_name, 'slug' => 'pa_' . strtolower( $product_attribute_name ), 'type' => 'select', 'order_by' => 'menu_order', 'has_archives' => true ); $wc_attribute = $woocommerce->post( 'products/attributes', $attribute_data ); if ( $wc_attribute ) : status_message( 'Attribute added. ID: '. $wc_attribute['id'] ); // store attribute ID so that we can use it later for creating products and variations $added_attributes[$product_attribute_name]['id'] = $wc_attribute['id']; // Import: Attribute terms foreach ( $product_attribute['terms'] as $term ) : $attribute_term_data = array( 'name' => $term ); $wc_attribute_term = $woocommerce->post( 'products/attributes/'. $wc_attribute['id'] .'/terms', $attribute_term_data ); if ( $wc_attribute_term ) : status_message( 'Attribute term added. ID: '. $wc_attribute['id'] ); // store attribute terms so that we can use it later for creating products $added_attributes[$product_attribute_name]['terms'][] = $term; endif; endforeach; endif; endforeach; $data = get_products_and_variations_from_json( $json, $added_attributes ); // Merge products and product variations so that we can loop through products, then its variations $product_data = merge_products_and_variations( $data['products'], $data['product_variations'] ); // Import: Products foreach ( $product_data as $k => $product ) : if ( isset( $product['variations'] ) ) : $_product_variations = $product['variations']; // temporary store variations array // Unset and make the $product data correct for importing the product. unset($product['variations']); endif; $wc_product = $woocommerce->post( 'products', $product ); if ( $wc_product ) : status_message( 'Product added. ID: '. $wc_product['id'] ); endif; if ( isset( $_product_variations ) ) : // Import: Product variations // Loop through our temporary stored product variations array and add them foreach ( $_product_variations as $variation ) : $wc_variation = $woocommerce->post( 'products/'. $wc_product['id'] .'/variations', $variation ); if ( $wc_variation ) : status_message( 'Product variation added. ID: '. $wc_variation['id'] . ' for product ID: ' . $wc_product['id'] ); endif; endforeach; // Don't need it anymore unset($_product_variations); endif; endforeach; } catch ( HttpClientException $e ) { echo $e->getMessage(); // Error message } |
You can find the script on Github repository
Thanks for the amazing tutorial. I am beginner in woocommerce. Can you please tell me where to put this set WP REST API integration code
Hi!
You need to create a new PHP file 🙂 I shared the code in Github repository. https://github.com/dominykasgel/woocommerce-api-import-products see import.php file. What do you want to achieve with the REST API?
where i need to create the php file? (dir)
This is a very good tutorial. I am not a programmer and it is very hard when you want to put your wordpress woocommerce store working but your supplier gives you a lot of code to achieve the Token authorization and to import your products. My problem is I am just starting in this json code and logic and I am just understanding the logic of that.
Hi, thank you for the amazing job you did here. Is a fact that there is nothing that can explain how this json files can be used. My supplier gave me all the codes to get the token and after that the products and variations. You say that I have just to create the pho file for the import as you explain and all the products will be upload/update/create woocommerce of my store?
Hi Bruno,
It depends on the format of your JSON file. This tutorial shows you how you can parse JSON files and with some PHP import them to WooCommerce. Would you like to send me your JSON file so that I can take a closer look and help you more?
Hi Dominykas,
The json file I have is like shown here.
And also, could you be so kind and tell me how can I say that The Product ID (from my supplier) is the Product SKU (for my woocommerce)?
Hi again,
I believe that I forgot to paste how my json file is presented. Here it goes:
[
{
“Id”:2977,
“EANs”:[“841055449″,”84101386”],
“Description”:”AGUA FRESCA edt spray 120 ml”,
“SetContent”:null,
“Price”:10.71,
“PVR”:20.50,
“Stock”:80,
“BrandId”:”10″,
“BrandName”:”Adolfo Dominguez”,
“Gender”:”Man”,
“Families”:[“Perfume”],
“Kgs”:0.3100,
“Ancho”:95, (->Width)
“Alto”:129, ( ->height)
“Fondo”:87, ( ->length)
“IVA”:21.00, ( ->VAT)
“Fecha”:”2008-10-14″, (->Date)
“Contenido”:”120 ml”, ( ->Content)
“Gama”:”5200″},
{…..
Sorry, can you please give a look to what I sent you earlier? If you need more info please tell me.
Regards
Bruno
Hi Bruno,
I don’t quite understand your question 🙂 When you create a product via the API, you can set the slug. So if your JSON looks like this: [{“Id”:2977,“EANs”:[“841055449″,”84101386”],“Description”:”AGUA FRESCA edt spray 120 ml” …}] … you’ll take the ID: 2977 and set the slug to 2977. Then the Product ID (from your supplier) = the Product SKU (for your woocommerce).. Hope this helps 🙂
How do you add/apply images to these newly created posts? I tried adding image urls to the .json file in the place I thought they should be but nothing ever generated through woocommerce. Any help would be greatly appreciated. Thanks for this awesome tut!
Hi Robert,
Are you using the REST API to upload the products and images? If so, you need to define ‘images’ URLs when creating a product. See: http://woocommerce.github.io/woocommerce-rest-api-docs/#product-properties and http://dominykasgel.com/wp-content/uploads/2017/09/REST-API-product-images.png . The API includes images generating too. If you don’t use the API, you can upload the images using https://codex.wordpress.org/Function_Reference/wp_insert_attachment, then adding the images IDs to a product https://gist.github.com/zarankumar/f80a73598152edf7d67a8c91dbf3be25 .
Thanks for that info. I actually got that figured out yesterday. It is working great with your code and a few additions to the json file! Thanks again for getting me started in the right direciton.
Now I’m running into the problem of every time I run the import.php a second time (to do another import) I get this error:
Error: Slug “size” is already in use. Change it, please. [woocommerce_rest_invalid_product_attribute_slug_already_exists]
Any idea how to fix this? How can I have the import run multiple times even if a certain attribute exists already (in this case “size”). I could not figure it out in the code. I’m sorry.
Thanks again for all your help
I’m having this error message too. I believe it doesn’t affect the importation of new content, but I might be wrong.
Robert, how did you manage to incorporate image importing into your code? Did you add a new function to the import.php file?
Hi Tales,
To get you started in the right direction, I wrote a few lines of code. My code explains how you can import an image to a simple product. Firstly, you need to add “image” to products.json file, then add $product[$key][‘images’][] = array( ‘src’ => (string) $pre_product[‘image’], ‘position’ => 0 ); in get_products_and_variations_from_json() function. See my working code example here: https://pastebin.com/c8z4ujja
Hi Tales,
I’m happy to hear that. If you want to run the import multiple times, then you need to comment out some code between #29 – #69 lines. The API doesn’t allow you to create the same attributes with the same data, so you need to ignore this part. However, in order to assign a product to a certain attribute, you need to pass $added_attributes as a second argument to get_products_and_variations_from_json( $json, $added_attributes ); functions. Solution: Get already added attributes from WooCommerce – http://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-product-attributes See how it’s already done and create the same $added_attributes variable. If you also need to create new attributes during your next import, then don’t ignore the part below // Import Attributes, but just get all product attributes and see if it’s already there if not, then add it.
Sorry, but it requires custom coding.
I want to run the code a few times but I can not. even when I put lines 29 and 69 in comments. can you help me
Also, do you know how I would set images for individual variations? Can I just add it to the json file or will I need to add code to handle that as well? Thanks again for your help.
Hi Robert,
Yes, just add the images to JSON file. I wrote a few lines of code with an explanation how you can add/import the images for simple products. See my code here: https://pastebin.com/c8z4ujja For variations, you need to follow the same way – have URLs in products.json file, then add the images to your main product and get the images IDs. You can retrieve the product data and image IDs once it’s imported. This line: $wc_product = $woocommerce->post( ‘products’, $product ); When you have the images IDs, then you need to assign them to a variation. Example here: http://woocommerce.github.io/woocommerce-rest-api-docs/#product-variation-properties … For every different case you need to modify the import script.
Hi Dominykas,
I need to change the way woocommerce works so that instead of getting the product price in the standard way it gets the price that I feed to it via an API. Is there a simpler way of achieving that?
Thanks!
What I mean is, is it easier to import just the price and integrate it to the existing products or get all the product information from the api?
Awesome job you did there, by the way 🙂
I’m glad to hear it’s useful! 🙂 It’s better to import and update the prices instead of getting the data from the API for every page load. You may have too many calls and it may slow down your website.
Thanks! I don’t think there would be that many products. How would one go about refreshing just the prices for every page load?
If you just want to show the price, but don’t use it for the checkout, then I don’t see a problem. Otherwise, I would setup a cron job and run a script to update the prices in the database. You can have only one call to the API just to update the prices in the DB and run it daily.
Last question for now I swear! Here’s an even trickier one. How do we add multiple variation types and conjoin them? I know it’s easy to accomplish manually when adding a product but I haven’t quite figured out how to make it work with this code.
For example I’d like to have this import generate variations based off of two separate types of attributes, in this case Size and Gender.
I need variations generated for every cross of both attribute types. So like this:
1. [Small] [Mens]
2. [Small] [Womens]
3. [Small] [Youth]
4. [Medium] [Mens]
5. [Medium] [Womens]
6. [Medium] [Youth]
From the WooCommerce API they provide this in their code:
“attributes”: [
{
“id”: 6,
“position”: 0,
“visible”: false,
“variation”: true,
“options”: [
“Black”,
“Green”
]
},
{
“name”: “Size”,
“position”: 0,
“visible”: true,
“variation”: true,
“options”: [
“S”,
“M”
]
}
],
However, when adding this “attributes” to my json file it does not work.
If you could help me solve this last problem you would be an absolute life saver!!
Hi Robert,
No problem. You need to modify the import script so that you can include more attributes and values. See my explanation here: https://pastebin.com/Tp062xFZ Sorry, but I can only show you how you can do it.
Hope this helps! 🙂
Hi Domynikas,
After quite a few hours, I think I got most of it right. I had a major setback due to the script not recognizing the url from the API as a file. So, I had to tweak with the first section of the code. I change the ‘file_exists()’ for a funtion to verify if the URL is valid.
This is what I came up with as a workaround, may be useful for others:
https://gist.github.com/anonymous/eb0da98c141bdf13548315a2b1248313
Don’t know what happened there. Can you edit the comment and add a link to the code snippet instead?
https://gist.github.com/anonymous/eb0da98c141bdf13548315a2b1248313
Sure, the code snippet has been added. 🙂
Thank you for sharing your code! Agree, it may be useful for others! 🙂
All else seems to be in place, I got it to add images to the products and product variables as well, thanks!
I’m having a hard time wrapping my head around this though:
I’m trying to create a script that updates the prices of my products and their variations via a cron job. I suppose I’d need this API?
http://woocommerce.github.io/woocommerce-rest-api-docs/?php#batch-update-products
I’ll have to call the Rest API and update it with the prices of my external API (since they vary wildly during the day I don’t think I’d need to compare them before updating). But, I’m at a loss on how to isolate the price variable and have it updated.
I’m happy to hear that! I think you are looking at the right page. Hmm, could you explain “how to isolate the price variable and have it updated”? Do you want to exclude the main product from updating? I see all parameters are optional except ID. Just tested the price updating for variable product and its variations. My code: https://pastebin.com/zLyYvSmf
Awesome! I guess I was overcomplicating this stuff. I was all tangled up on new API POST authentications and what not. This code seems to be working properly.
https://pastebin.com/vX28gMy9
The way it works now, I have to set the prices manually in the script. How would you do to have the script look for the prices on the external API instead?
Hey Tales, I’m glad that you managed to make it work properly! 🙂
Answering your question, it depends on the data you need. In order to change the price, you need to know the product ID. Can you get it from your external API? If not, then you need some kind of parameter to sync the price from your external API to the right product in your store. It could be SKU or product title. When you have the product id you can change the price.
Hey Dominykas,
I’ve been banging my head over this and I got this script to work:
https://pastebin.com/nHdSxgFc
As you can see, it’s a nightmare if you need to update anything, as each update call is linked to a specific product ID.
I was trying to update the regular_price based on the SKU, but I can’t get it to work. My api returns the values in this format btw: https://pastebin.com/HsDissxM
How could one get the SKU and regular_price keys from the API and update the price in the database based on that? I though about something like a foreach loop and an if statement comparing the SKUs and updating the price, but I just can’t pull it off ~.~
Hello,
Nice tutorial. I getting this error when execute import.php file:
Fatal error: Class ‘Automattic\WooCommerce\Client’ not found in /
Should I put the code in Woocommerce template file?
Thanks
I’m glad to hear that you find the article useful. This means a PHP wrapper for the WooCommerce REST API is missing. There are wrappers for Ruby and Python as well. In order to use the API in PHP, you need to install the wrapper. Take a look at installation: https://github.com/woocommerce/wc-api-php#installation The best way is to use composer (https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx) and install it in the same directory as the import.php file.
Thanks for responding. Yes, I figured that later after posting here :). Seems to be fine now. Thanks again.
Thanks for amazing tutorial .
My question is bit off topic but I guess you would be able to help me .
I am trying to import products from Woocommerce site via API and importing it to my php site.
I have created a file say xx_api.php which has basic info
true,
‘version’ => ‘wc/v2’,
‘query_string_auth’ => true // Force Basic Authentication as query string true and using under HTTPS
]
);
$abc = ($woocommerce->get(‘products/categories’));
echo json_encode($abc, JSON_FORCE_OBJECT);
?>
Now this returns 10 Products . How do i setup auto pagination or somehow make the script load all the products ??
Hi Monarch,
If you go to this page: https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-products you’ll see there’s a per_page parameter (Maximum number of items to be returned in result set. Default is 10.) Try to change it to -1 (not sure, haven’t tested) or 1000. Hope this helps 🙂
I’m trying to connect the categories to the products, but I don’t get why it isn’t working. I created the categories before the products and then give the ID to connect the product to a category, but still doesn’t work.
Hi Samir,
Can you add your code to pastebin and copy the link here?
https://pastebin.com/BqJJCBb3
The problem is that I can actually create the categories, but the ID doesn’t get matched with the product.
Thank you for that fantastic post .
I have a problem and hope you can give me a solution
I have a financial software for managing products now i have built an website based on woocommerce. I want my online store to get products automatically from my software .
What software do you use?
It is web based non commercial software . It is new on market
Hi, I have this error:
PHP Fatal error: Uncaught exception ‘Automattic\WooCommerce\HttpClient\HttpClientException’ with message ‘Error: SKU no válido o duplicado. [product_invalid_sku]’
how can solved this?
Make sure your SKU is unique and there’s no product with the same SKU in your WooCommerce store 🙂
Hello sir
I am making an app. Using woocommerce rest api in “node.js”
And I want to add product variations on my product page. Can you help by generating the code.
The code is already in the API documentation 🙂 See here: http://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#create-a-product-variation
Hi Dominykas, congratulations on the excellent work. I am trying to put in my system but I do not understand the authentication part, I only have one Token and the authentication mode is the basics, can you guide me?
Hi Erlan, I think I’ll write a short blog post about the auth part this week. In short, you need to get composer, then download the Rest API library for PHP (command: composer require automattic/woocommerce) and then you can do the auth part in PHP. A short example is here: http://woocommerce.github.io/woocommerce-rest-api-docs/?php#libraries-and-tools More info: http://woocommerce.github.io/woocommerce-rest-api-docs/?php#authentication
Hi Dominykas,
Glad to see you are still working on this.
I have a few questions: is since I am not uploading a product.json file I am retrieving it from a remote API. How do I get that file? I know your code gets the file from the local directory but I am trying to connect to an outside API.
other question is can I put this into my functions.php or should i call this php script else where? thank you!
Great post! But unfortunately I’m having a problem: I’m running the supplied code without any change, the json that I’m using is also the one provided in the example, I just modified the WooCommerce API credentials, just to test the connection and operation of the API token.
When executing the code it imports the attribute normally, but at the time of importing the products it only imports the first one and issues an error: “Syntax error”. this error is still issued to the first product, even though it is being imported successfully. I can not find what’s wrong. is even more difficult to understand since I am using the example without any change. I’ll be grateful if anyone can help me with this.
When I debug the code I can see that the error comes from inside the wrapper, more precisely in function request, the $ response variable returns (code = 200, Body =Fatal error: Call to undefined function array_replace_recursive() in /home/jmx/public_html/wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-data.php on line 654)
Hi Luis, try to change the WC API version to ‘wc/v2’ in $woocommerce = new Client(…). Looks like I made a typo.. I just tested the script with ‘wc/v2’ and it works really well. You’ll get a syntax error if you run it with ‘wc/v1’.
Thanks for listening! The WC API version was already in ‘wc / v2’. But luckily I discovered the problem. The version of PHP that was running on my server was 5.2.17 and it was nessesssario to upgrade to some 5.3 or higher. In case I’m using it now to 5.6 and everything is working right.
Hello, Dominykas. Thanks for sharing.
I have a problem in line 43 of file import.php: PHP Fatal error: Cannot use object of type stdClass as array.
What can it be?
Thanks.
Replace $added_attributes[$product_attribute_name][id] –to–
$added_attributes[$product_attribute_name]->id
Great post, it’s really userful for a Woocommerce newbie like me 🙂
Based on your code, I’m trying to write an script to update the existing products and its variations (>1,300 products with multiple variations).
I read that is not possible to update one product and its variations at same time, so in first place I use batch update for the products and, after, I do a batch update for the variations of one product every time.
This means a lot of time that exceeds the limits allowed by my server.
Do you know any alternative way for make this import faster?
Thank you very much!
How to update existing product on woocommerce using json product parent id can you help me to solve this?
Need help with plugin development…
How can I send product information from Woocommerce store to my own marketplace(which is in asp.net)??
Instead of JSON, is it possible to also import products using CSV. I have seen a tutorial for creating a custom dashboard with products using WooCommerce rest api (https://www.cloudways.com/blog/custom-dashboard-using-woocommerce-php-rest-api/ ). I was wondering if you could also add product import functionality to it.
Yes, it’s possible. You just need to parse CSV instead of JSON.
Hi,
I am working with woocommerce, i am interested to import products from Bangood by Api to Woocommerce, is that possible with this technique? i have basic knowledge of php.
Thanks.
I haven’t used Bangood API so I don’t know.
Thank you for the code, I inserted the products very simply using the script. My question is how to use the script to update the already imported products, insert new and update the inventory of products. Thank you in advance for your reply.
Happy to hear that! You can find this in the documentation 🙂 Take a look here: https://woocommerce.github.io/woocommerce-rest-api-docs/?php#update-a-product. “Update a product – This API lets you make changes to a product.” HTTP Request: PUT “/wp-json/wc/v2/products/” code: $data = [ ‘regular_price’ => ‘24.54’ ]; print_r($woocommerce->put(‘products/794’, $data)); Change regular_price to stock_quantity or whatever you want to change.
Thank you for the quick response and the suggestions. I’ll try to make changes to the code. Please for another help. I want to take the json code from a url address. I saw that there is a code for it in the comments, but I do not manage to figure out how to write the url for my site. Now I work locally and the api address that gives the json code is http://trinity-slim/ api /products. How should I write the url address so I can download the json code from a url instead of a file. Thank you for your help.
Greetings
No problems 🙂 An example from WordPress Codex:
$url = ‘http://example.org/api’;
$response = wp_remote_get( esc_url_raw( $url ) );
/* Will result in $api_response being an array of data,
parsed from the JSON response of the API listed above */
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
Hello,
I want to use your code, I have api keys from my woocommerce site but I have no idea where I need to put the import.php page. Please help me. Thank you.
Hi Romana,
Put it in WordPress root directory, but you also need to install WooCommerce REST API PHP wrapper. The easiest way is to use Composer. Setup docs here: https://github.com/woocommerce/wc-api-php
Me again. I have a series of categories that are given in Json like this: “categories”: [{ “id”: 53, “name”: “Active Network Equipment”,”slug”: “active_message_oprema”},
{“id”: 60, “name”: “Wireless WIFI equipment”, “slug”:”wireless_wifi”}]
Please help me put in your code. Thank you.
You can add categories first. See: https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-product-category, then launch this import script and assign products to your categories
Hi Dominykas,
I launched your script and managed to import products in my woo site. In my woocommerce site I only have simple products. The script imports the products but gives me an error “Notice: Undefined variable: added_attributes in C: \ xampp \ htdocs \ woo-api-import-products \ import.php on line 71”. Please, can I somehow escape this error?
I created the categories before the products and then give the ID to connect the product to a category, but still does not work. It does not report a code error, but the categories are not entered. Can I send you a code here? Thank you for your help.
Yes, upload your JSON file and import PHP script to Pastebin or somewhere else and copy here. If you have only simple products, then you don’t need to import the attributes. Looks like you haven’t removed that part from the script. Remove it. Can’t help without seeing the code..
https://pastebin.com/pp1iY2tZ
In the products.json file, I tried to import IDs for categories, but I received an error message. Many times I saw the documentation of the woocomerce but I can not figure out how to use the code. Please help me, I am new to php language.
Hi, I have one question. when I use your this code from GitHub. I got one fatal error. and that is this Fatal error: require(): Failed opening required ‘D:\website\nextbuild\wp-content\plugins\importproduct/vendor/autoload.php’ (include_path=’C:\xampp\php\PEAR’) in D:\website\nextbuild\wp-content\plugins\importproduct\main.php on line 14
can you tell me? which autoload.php file i have to connect?
Hi Abdullah,
You need to install WooCommerce API PHP Client in the root folder of WordPress install. You need to use Composer, so first install Composer if you don’t have it, then install WooCommerce API – PHP Client using this command: composer require automattic/woocommerce
I have installed composer and also i used composer require automattic/woocommerce this command to install woocommerce. is it right?
Yes. Try not to do the import, but create a new file and test your REST API to make sure it works: https://woocommerce.github.io/woocommerce-rest-api-docs/#libraries-and-tools
and one more thing I want to know. can I import data from an external JSON API? using this technique.
let me explain you very clearly. if I use this technique to get data from an external API. Will it add here? http://prntscr.com/jilf98 and it will be looped on the website shop page?
It is possible
Thank you for your suggestion to remove the part of the code “import the attributes” because I only have simple products. I managed to do that and did not receive any more error messages. I put the modified code on the address https://pastebin.com/zwPQKKpg
But I still can not add categories. Please for help.
Hi Dominykas,
Thanks for sharing your work! It’s great!
I’m struggling with Woocommerce API because.
My problem is: I need to update “external_url”, “regular_price” and “sale_price” in almost 7100 “external products” using a JSON that comes from a big website, 4 times a day.
I’m not a developer, but I could build a code to put it running, but just for few products, when I try with more (1000 as example) it’s not working because I’m getting “504 Gateway Time-out” always.
Do you already use API for so many records?
Do you know how can I handle it?
p.s. I already changed the maximum execution limit in php, set 900, but still timeout in 300. 🙁
best regards
Thanks
I have a woocommerce store at https://bigthicketcoin.com/shop and I want to pull in products from another source who has provided me a test site and live key.
How would you recommend I GET that into my wordpress site. I am slightly new to REST API/JSON but I know my basics..
Thanks for any help on this.
The other source is a website with a store management system. I forgot to add that. They have provided a testlink and live public/private key.
Hey, this codes are for importing to woocommerce backend right?
What about if I want to generate json for all woocommerce product archive based on specific tag?
Im trying to create a woocommerce tag widget AJAX but I’m stuck at importing the listed product based on tag.
Hi Dominykas,
Thanks for great sharing! It’s really help alot!
I have to ask how can add image to variation type product. I have tried this
$product_variations[‘attributes’][] = array(
‘id’ => (int) $added_attributes[$attribute_name][‘id’],
‘name’ => “colors”,
‘option’ => (string) $attribute_value,
‘image’ =>array(array(‘src’=>’image_url’,’position’ => 0))
);
$wc_variation = $woocommerce->post( ‘products/’.$wc_product->id .’/variations’, $variation );
But its not saving variation image
Can you please help me in solving this.
Hi Dominykas
I am new to API integration. Have an API and work fine in postman with header as Content-Type : application/json and X-Auth-Token :xxxxxx usin GET method
I need use the same and add and update product from this api and also send sales detail back using post method
Can you please advice
Did you take a look at WC docs http://woocommerce.github.io/woocommerce-rest-api-docs/#update-a-product
Hello,
really nice and helpful article!
It’s the first time i’m going to use REST API and i’m a beginner. I would like to ask a question.
I have a store and a vendor who provides his products feeds through a rest.php file. This case can work for my case too or i need to create something else?
Thank you in advance.
Hi Dominykas,
i’m educating myself doing post get requests with woocommerce rest api doing well, using postman for request pasting json data to body of request.
I can’t figure how to create variable product with variations in single request using this wip JSON code: https://pastebin.com/80xesyQi
Or which way should I move to create variations for newly created product how can I know it’s newly created id to parent it?
Hello friend, excellent work. I congratulate you. I have a question, I want to execute this code several times for each time I add new products. My question is how could I validate that the products I enter are not repeated in Woocommerce. Thank you.
Nice tutorial, can you please guide me how to import order from to woo from API?
Hi there,
Thanks for sharing this , it’s really useful !
I need to eliminate all variable products and use products of type simple only .
Is there an easy way for me to do this , either by setting if product type = null or hardcoding as simple or something ?
There’s a lot of code based on product type in the script, and i’m a bit of a novice with php :/
An example of the json I need to import is here – https://pastebin.com/LHMxEWTH
Thanks!
Hi,
Great tutorial. I’ve spent 2 weeks researching for info on this topic and all I was able to find was how to export from WC. One quick question: I noticed you said that this can “import” products into woocommerce. what about only displaying the product info on post types or product archives? the reason for this is to manage the inventory from the supplier’s DB so I only want to display the product info including dz and cs price color images, etc. I’m also trying to integrate with SOAP XML for the same goal; displaying the product. Thanks in advance.
Hello. I try to load attributes and I get an error that such a slug exists, how to make a check for the existence of such an attribute with this name and slug?
https://prnt.sc/npbnfv
Hello. I try to load attributes and I get an error that such a slug exists, how to make a check for the existence of such an attribute with this name and slug?
https://prnt.sc/npbnfv
I have a client that wants me to connect his woocommerce store to an external supllier rest api. How do i do it?
can you help me with this a little further?
Hi!
Im using a similar process to import products to woocommerce.
Now I’m facing an issue:
I need to have the name and the description of each product translated in different languages and I can’t seem to find the answer. I’m using Polylang Free Version and I don’t know if I need to use its API and integrate it with my importer code or create a new file.
Any help would be great!
Great work
Hey Dominykas, can you help me with integrate Product from https://portal.neo-wws.de/neo-server-prod/ws-api/Rest_API.json?
I would like to pay you for it too 🙂
hello, how can i solve this problem with this page showing? eye
Hello,
I have this error.
PHP Fatal error: Uncaught Error: Class ‘automattic\Client’ not found in /var/www/html/import2.php:10
Line 8, 9, 10 is.
function getWoocommerceConfig()
{
$woocommerce = new Client(