pythonwordpresswoocommercewordpress-rest-apiwpml

python, woocommerce: how to add categories with translations?


I need a python snippet to create categories with translation. Python 3.8 with woocommerce package.

Wordpress with woocommerce plugin in version 7.3

WPML Multilingual CMS: 4.5.14

I have this snippet in python:

from woocommerce import API

# create an instance of the API class
wcapi = API(
    url="FQDN",
    consumer_key="yourconsumerkey",
    consumer_secret="yourconsumersecret",
    wp_api=True,
    version="wc/v3"
)

# create a dictionary with the category data for the main language
category_data_en = {
    "name": "Category Name in English",
    "parent": 0,
    "meta_data": [
        {
            "key": "_wpml_language",
            "value": "en"
        },
        {
            "key": "_wpml_translation_status",
            "value": "0"
        },
        {
            "key": "_wpml_element_type",
            "value": "tax_category"
        }
    ]
}

# create the category using the WooCommerce API for the main language
new_category_en = wcapi.post("products/categories", category_data_en).json()

# create a dictionary with the category data for the translation
category_data_pl = {
    "name": "Category Name in Polish",
    "meta_data": [
        {
            "key": "_wpml_language",
            "value": "pl"
        },
        {
            "key": "_wpml_translation_of",
            "value": new_category_en.get("id")
        },
        {
            "key": "_wpml_translation_status",
            "value": "1"
        },
        {
            "key": "_wpml_element_type",
            "value": "tax_category"
        }
    ]
}

# create the translation using the WooCommerce API
new_category_pl = wcapi.post("products/categories", category_data_pl).json()

and it creates two categories in the English language on my website. What am I doing wrong? result of running this snippet

I can see that in my WPML plugin setting there is the info: WooCommerce Multilingual Not installed Is it necessary to install it to get those categories created properly?


Solution

  • What I had to do is:

    1. create categories in 'en' language (added: 'lang':'en')
    2. I had to loop over those categories and create new ones in pl (added: 'lang':'pl' and 'translation_of': id_category_en