WooCommerce REST API – Import products from JSON

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.


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 for the new WP REST API integration (WooCommerce 2.6 or later):

1. Parse JSON

Convert JSON string to PHP array.

2. Get all product attributes from JSON

We need to get all product attributes names and values from JSON file.

3. Get products and variations from JSON for importing

4. Merge products and product variations

Used to loop through products, then loop through product variations.

5. A simple function to print status message

Import products to WooCommerce using the API

You can find the script on Github repository

Join the Conversation


  1. 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

  2. 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.

  3. 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?

    1. 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?

      1. 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)?

      2. Hi again,

        I believe that I forgot to paste how my json file is presented. Here it goes:
        “Description”:”AGUA FRESCA edt spray 120 ml”,
        “BrandName”:”Adolfo Dominguez”,
        “Ancho”:95, (->Width)
        “Alto”:129, ( ->height)
        “Fondo”:87, ( ->length)
        “IVA”:21.00, ( ->VAT)
        “Fecha”:”2008-10-14″, (->Date)
        “Contenido”:”120 ml”, ( ->Content)


          1. 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 🙂

  4. 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!

    1. 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 .

      1. 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

        1. I’m having this error message too. I believe it doesn’t affect the importation of new content, but I might be wrong.

        2. Robert, how did you manage to incorporate image importing into your code? Did you add a new function to the import.php file?

          1. 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

        3. 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.

          1. 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

      2. 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.

        1. 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.

  5. 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?


    1. 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 🙂

      1. 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.

        1. Thanks! I don’t think there would be that many products. How would one go about refreshing just the prices for every page load?

          1. 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.

  6. 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”: [
    “name”: “Size”,
    “position”: 0,
    “visible”: true,
    “variation”: true,
    “options”: [

    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!!

  7. 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?

    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.

    1. 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

      1. 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.

        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?

        1. 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.

  8. Hey Dominykas,
    I’ve been banging my head over this and I got this script to work:

    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 ~.~

  9. 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?


    1. 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.

      1. Thanks for responding. Yes, I figured that later after posting here :). Seems to be fine now. Thanks again.

  10. 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
    ‘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 ??

  11. 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.

  12. 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 .

  13. 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?

  14. 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.

  15. 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?

  16. 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!

  17. 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.

    1. 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)

      1. 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’.

        1. 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.

    1. Replace $added_attributes[$product_attribute_name][id] –to–

  18. 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!

  19. Need help with plugin development…
    How can I send product information from Woocommerce store to my own marketplace(which is in asp.net)??

  20. 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.


  21. 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.

    1. 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.

  22. 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.

    1. 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 );

  23. 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.

  24. 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.

  25. 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.

    1. 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..

      1. 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.

  26. 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?

    1. 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

  27. 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.

  28. 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


  29. 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.

  30. 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.

  31. 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.

  32. 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.

  33. 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

  34. 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.

  35. 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?

  36. 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.

  37. 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


  38. 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.

  39. I have a client that wants me to connect his woocommerce store to an external supllier rest api. How do i do it?

  40. 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

  41. 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(

Leave a comment

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