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

How to add custom product sorting options in WooCommerce

By default, WooCommerce comes with 6 sorting options:

  • Sort by popularity
  • Sort by average rating
  • Sort by newness
  • Sort by price: low to high
  • Sort by price: high to low

In this example, I’ll add an extra option to sort by sale status.

Adding a new sorting option

woocommerce_catalog_orderby hook gives you control over the default sorting options to display. In order to add a new option, you need to add it to the current options array.


Now add the following code to order by the _sale_price custom field.


Advanced sorting

However, if your sorting needs are more advanced, then you can hook into pre_get_posts instead of woocommerce_get_catalog_ordering_args.

The pre_get_posts hook gives developers access to the $query object and possibility to modify the query. It’s really powerful and useful for altering the main loop and creating custom queries. See the docs here.

In this example, we’ll show products from a given category ‘Cars’ and sort them by sale status.