For help with hosting and deployment join our discord channel.

Create WooCommerce Product Categories Using the API

Created on September 5, 2024

python
async

Import to edit/run function

Getting the API Key

Before interacting with the WooCommerce API, you'll need to generate your API credentials (consumer key and consumer secret). Follow the steps in this WooCommerce REST API documentation to get the API key.

Structuring the API Call

To create a product category using the WooCommerce API, make a POST request to the following endpoint:

  • URL:
https://yourwebsite.com/wp-json/wc/v3/products/categories
  • Authentication:
    The API requires basic authentication using your consumer key and consumer secret.

  • Parameters:
    The body of the request should contain the following JSON data:

  • name: The name of the category.

  • description: A brief description of the category.

  • slug: (Optional) URL-friendly version of the name.

  • parent: (Optional) If you are creating a subcategory, pass the ID of the parent category.

  • image: (Optional) If you want to add an image to the category, include the image.src field with the image URL.

This is how it should look:

curl -X POST https://yourwebsite.com/wp-json/wc/v3/products/categories \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{
  "name": "New Category",
  "description": "This is a new category created via the API.",
  "slug": "new-category"
}'

Handling Images and Other Data

The WooCommerce API also allows you to add images to categories by passing an image parameter.

category_data = {
    'name': 'Category with Image',
    'description': 'This category has an image',
    'slug': 'category-with-image',
    'image': {
        'src': 'https://example.com/path/to/image.jpg'
    }
}

Function Code

import requests
import json
import os


def handler(request):
    """ sample data in request body: 
    {
        "categories": [
            {
                "name": "Main Category",
                "description": "A main category",
                "slug": "main-category",
                "image": {
                    "src": "https://media.istockphoto.com/id/518378319/photo/t-shirt.jpg?s=612x612&w=0&k=20&c=J6Xzvnrj18Hf3qYKCfglsI4r60fbJ2i4Aytb4zYWQ3g="
                }
            },
            {
                "name": "Sub Category",
                "description": "A subcategory of Main",
                "slug": "sub-category",
                "parent": 123  # ID of the parent category
            }
        ]
    }
    """


    data = request['body']
    print(type(data))
  
    # WooCommerce API credentials from environment variables
    consumer_key = os.getenv('CONSUMER_KEY')
    consumer_secret = os.getenv('CONSUMER_SECRET')
    base_url = os.getenv('STORE_URL') + '/wp-json/wc/v3/products/categories'
    print(base_url)
  
    # Iterate over the category data from the request
    for category in data['categories']:
        category_data = {
            'name': category['name'],
            'description': category.get('description', ''),
            'slug': category.get('slug', ''),
            'parent': category.get('parent', 0),
            'image': category.get('image', None)  # Optional image URL
        }
        
        # Make the POST request to create the category
        response = requests.post(
            base_url,
            auth=(consumer_key, consumer_secret),
            headers={'Content-Type': 'application/json'},
            data=json.dumps(category_data)
        )
        
        # Print the response (or handle it as needed)
        print(response.json())