WPML

WPML Multilingual & Multicurrency for WooCommerce is compatible with the WordPress REST API. Using the REST API, you can now create, read, update, and delete translated WooCommerce content.


This document is intended for developers who want to leverage these features and offer multilingual WooCommerce experience in their plugins, sites and applications.

Requirements


To use the REST API with WPML Multilingual & Multicurrency for WooCommerce you need the following:

Setting Up The Client Library


As mentioned, you need the WooCommerce REST PHP client library. This library is a PHP wrapper which allows interaction with the WooCommerce REST API in a more straightforward way. You can use other client libraries as well.

Setting up the library inside your application involves a few steps:

  1. Download the library files to your site’s server using the following Composer command:
    Bash
    composer require automattic/woocommerce
  2. Generate the Consumer Key and Consumer Secret values. To do this, go to WooCommerceSettingsAdvancedREST API keys and click Add key. In the form that appears, enter the Description, User and Permissions you want to grant the user, and click Generate API key.
  3. Include the library auto-loading file, autoload.php, at the start of your PHP code using the require function, and create the client with your site’s address and the generated Consumer Key and Consumer Secret values.
    WCML REST API- including autoloading filePHP
    require __DIR__ . '/vendor/autoload.php';
    
    use Automattic\WooCommerce\Client;
    
    $woocommerce = new Client(
    	'https://example.com',
    	'ck_your_consumer_key',
    	'cs_your_consumer_secret',
    	[
    		'version' => 'wc/v3',
    	]
    );
  4. Configure the options for using the library. You can find the description of all the options on the official page (opens in a new tab).

Using the REST API


Now that you set up the library in your PHP code, you can start developing different actions for your code to perform. The following list features all main actions you can perform using REST API and WPML Multilingual & Multicurrency for WooCommerce.

View orders


By adding the lang parameter to the request, you can return the contents of orders in specified languages. The only condition is that products are translated into the respective language. One application of this is seeing the orders in the site’s default language.

Example: Get only the orders placed in French.

PHP
$orders = $woocommerce->get('orders', array( 'per_page' => 25, 'lang' => 'fr' ) );

Related WooCommerce Documentation: List all orders (opens in a new tab)

View Single Order


By providing a lang parameter to the request, if the order was placed in a different language, all items, if they exist, will be displayed as translations in the specified language.

Example: See contents of order #110 in English.

PHP
$order = $woocommerce->get('orders/110', array( 'lang' => 'en' ) );

Related WooCommerce Documentation: Retrieve an order (opens in a new tab)

Get products


By adding the lang parameter, you can get products in a specified language. To get all products in all languages the lang parameter must be set to all.

Example: Get only the Spanish products.

PHP
$products = $woocommerce->get('products', array( 'per_page' => 25, 'lang' => 'es' ) );

Related WooCommerce Documentation: List all products (opens in a new tab)

View Single Product


The returned data includes the product’s language (lang) and its translations: the ID of the product in each language of its translation group, including its own. Prices in secondary currencies are in meta_data (see Prices in Secondary Currencies).

Example:

PHP
$product = $woocommerce->get( 'products/14' );

Along with the WooCommerce product fields, the answer includes:

View Single ProductPHP
{
	"id": 14,
	"name": "Zip-Up Hoodie",
	"type": "simple",
	"status": "publish",
	"sku": "HP-HD-ZIP",
	…
	"lang": "en",
	"translations": { "de": "121", "en": "14", "fr": "122" }
}

Related WooCommerce Documentation: Retrieve a product (opens in a new tab)

Get Product Taxonomy Terms (Product Categories, Tags, Attributes, Shipping Classes)


By adding the lang parameter, you can get product taxonomy term in a specified language. To get all terms in all languages the lang parameter must be set to all.

Example: Get categories in all languages.

PHP
$categories= $woocommerce->get('products/categories', array( 'per_page' => 10, 'lang' => 'all' ) );

Related WooCommerce Documentation: List all product categories (opens in a new tab)

Top Sellers Reports


By adding the lang parameter, you can get reports in a specified language.
Top SellersPHP
$query = [ 'lang' => 'fr' ];
$woocommerce->get( 'reports/top_sellers', $query );

Related WooCommerce Documentation: Retrieve top sellers report (opens in a new tab)

Products Totals Reports


By adding the lang parameter, you can get reports in a specified language.
Products TotalsPHP
$query = [ 'lang' => 'fr' ];
$woocommerce->get( 'reports/products/totals', $query );

Related WooCommerce Documentation: Retrieve products totals (opens in a new tab)

Create products


Three parameters are supported when creating a product:
  • lang – the respective lang value will be set for the product. If omitted, the default language of the site will be used.
  • translation_of (optional) – the product will be created as a translation of an existing product, having the ID provided by the value of translation_of. If translation_of is omitted, the product is created as part of a new translation group (trid).
  • custom_prices – sets prices in secondary currencies. See Prices in Secondary Currencies.

Example:
Create ProductsPHP
$data = [
	'name'              => 'Stoneware Coffee Mug',
	'type'              => 'simple',
	'status'            => 'publish',
	'sku'               => 'HP-HG-MUG',
	'regular_price'     => '16.00',
	'manage_stock'      => true,
	'stock_quantity'    => 60,
	'short_description' => 'Hand-glazed stoneware mug, 350 ml.',
	'description'       => 'A sturdy stoneware mug with a hand-dipped glaze. Holds 350 ml, dishwasher and microwave safe.',
	'categories'        => [ [ 'id' => 32 ] ],
	'lang'              => 'en'
];
$product = $woocommerce->post( 'products', $data );

To add a product as a translation of another product, you need to pass the translation_of parameter. If the product that was created with the previous call has an ID of 121, the following would be the code for adding a translation:

Creating a product as translation of another onePHP
$data = [
	'name'              => 'Steingut-Kaffeebecher',
	'slug'              => 'steingut-kaffeebecher',
	'status'            => 'publish',
	'short_description' => 'Handglasierter Becher aus Steingut, 350 ml.',
	'description'       => 'Ein robuster Becher aus Steingut mit handgetauchter Glasur. Fasst 350 ml, spülmaschinen- und mikrowellengeeignet.',
	'categories'        => [ [ 'id' => 38 ] ],
	'lang'              => 'de',
	'translation_of'    => 121
];
$product = $woocommerce->post( 'products', $data );

Note that if the categories are already translated, you don’t need to specify them explicitly when adding the translation if the Copy taxonomy to translations option is set in WPML. They will be added automatically.

One product translation per language. If the product already has a translation in the language you send, the call is refused with HTTP 400 wcml_translation_exists and nothing is created. The message names the ID of the existing translation. Update the existing translation instead, with PUT products/<id>.

Related WooCommerce Documentation: Create a product (opens in a new tab)

Variable Products

Create product variations with local attribute


Three parameters are supported when creating a product variation:
  • lang – the respective lang value will be set for the product variation. If omitted, the default language of the site will be used.
  • translation_of – not needed for variations. Create the variations on the original product only. When you create the translated variable product, WPML creates its variations (see Create Product Variations with Global Attribute).
  • custom_prices – sets prices in secondary currencies on the variation. See Prices in Secondary Currencies.

Example:
Create VariationPHP
$data = [ 'lang'          => 'en',
          'regular_price' => '10',
          'attributes'    => [ [ 'name' => $local_attribute_name, 'option' => 'red' ] ]
];
$woocommerce->post( "products/{$variable_product_id}/variations", $data );

To translate the variable product, create its translation with the translation_of parameter set to the ID of the original variable product, not of a variation:

Translate Variable ProductPHP
$data = [
	'name'           => 'Translation of Variable Product',
	'type'           => 'variable',
	'description'    => 'Translate of Product Description',
	'lang'           => 'fr',
	'translation_of' => $variable_product_id,
	'attributes'     => [
		[
			'name'      => $local_attribute_name,
			'visible'   => true,
			'variation' => true,
			'options'   => [
				$translation_of_red
			]
		]
	]
];
$woocommerce->post( 'products', $data );

Related WooCommerce Documentation: Create a product variation (opens in a new tab)

Create Product Variations with Global Attribute


First, you need to create and translate the global terms (see Creating Taxonomy Terms). Then, you can create the variable product by following the example below. It uses the attribute IDs (Color is 1, Size is 2) and the term names in the default language:
Create variable productPHP
$data = [
	'name'               => 'Merino Crew Sweater',
	'type'               => 'variable',
	'status'             => 'publish',
	'sku'                => 'HP-KN-MERINO',
	'short_description'  => 'Fine-gauge merino wool, crew neck.',
	'description'        => 'A light, fine-gauge sweater knitted from 100% merino wool. Ribbed cuffs and hem, regular fit.',
	'categories'         => [ [ 'id' => 25 ] ],
	'lang'               => 'en',
	'attributes'         => [
		[ 'id' => 1, 'visible' => true, 'variation' => true, 'options' => [ 'Blue', 'Green' ] ],
		[ 'id' => 2, 'visible' => true, 'variation' => true, 'options' => [ 'S', 'M', 'L' ] ]
	],
	'default_attributes' => [
		[ 'id' => 1, 'option' => 'Blue' ],
		[ 'id' => 2, 'option' => 'M' ]
	]
];
$woocommerce->post( 'products', $data );

Then we need to create product variations on the original product. If the original product has an ID of 124, then the following would be an example of the code:

Create product variationsPHP
$data = [
	'create' => [
		[ 'sku' => 'HP-KN-MERINO-BLU-S', 'regular_price' => '65.00', 'manage_stock' => true, 'stock_quantity' => 8,  'lang' => 'en', 'attributes' => [ [ 'id' => 1, 'option' => 'Blue' ],  [ 'id' => 2, 'option' => 'S' ] ] ],
		[ 'sku' => 'HP-KN-MERINO-BLU-M', 'regular_price' => '65.00', 'manage_stock' => true, 'stock_quantity' => 12, 'lang' => 'en', 'attributes' => [ [ 'id' => 1, 'option' => 'Blue' ],  [ 'id' => 2, 'option' => 'M' ] ] ],
		[ 'sku' => 'HP-KN-MERINO-BLU-L', 'regular_price' => '65.00', 'manage_stock' => true, 'stock_quantity' => 10, 'lang' => 'en', 'attributes' => [ [ 'id' => 1, 'option' => 'Blue' ],  [ 'id' => 2, 'option' => 'L' ] ] ],
		[ 'sku' => 'HP-KN-MERINO-GRN-S', 'regular_price' => '65.00', 'manage_stock' => true, 'stock_quantity' => 6,  'lang' => 'en', 'attributes' => [ [ 'id' => 1, 'option' => 'Green' ], [ 'id' => 2, 'option' => 'S' ] ] ],
		[ 'sku' => 'HP-KN-MERINO-GRN-M', 'regular_price' => '65.00', 'manage_stock' => true, 'stock_quantity' => 9,  'lang' => 'en', 'attributes' => [ [ 'id' => 1, 'option' => 'Green' ], [ 'id' => 2, 'option' => 'M' ] ] ],
		[ 'sku' => 'HP-KN-MERINO-GRN-L', 'regular_price' => '65.00', 'manage_stock' => true, 'stock_quantity' => 7,  'lang' => 'en', 'attributes' => [ [ 'id' => 1, 'option' => 'Green' ], [ 'id' => 2, 'option' => 'L' ] ] ]
	]
];
$woocommerce->post( 'products/124/variations/batch', $data );

Now the variable product and its variations have been created in English. To translate it, create the translated product with lang and translation_of, as in the example below. WPML creates the translated variations, links each one to its original variation, and copies the SKU, price, stock and attribute terms in that language:

Create translation of a variable productPHP
$data = [
	'name'              => 'Pull col rond en mérinos',
	'slug'              => 'pull-col-rond-en-merinos',
	'type'              => 'variable',
	'status'            => 'publish',
	'short_description' => 'Maille fine en laine mérinos, col rond.',
	'description'       => 'Un pull léger en maille fine, 100 % laine mérinos. Poignets et bas côtelés, coupe classique.',
	'categories'        => [ [ 'id' => 55 ] ],
	'lang'              => 'fr',
	'translation_of'    => 124
];
$woocommerce->post( 'products', $data );

Related WooCommerce Documentation: Batch update product variations (opens in a new tab)

What an Update Carries to Translations

Write prices, attributes and variations to the original product. WPML copies them to every translation in the same request. For the full update flow, see Update Products with the WooCommerce REST API.

Example: Change the price and stock of an original simple product (ID 121) and of an original variation (ID 125 of the variable product 124), and add a variation to the original.

Update the originalPHP
$woocommerce->put( 'products/121', [ 'regular_price' => '18.00', 'sale_price' => '15.00', 'stock_quantity' => 45 ] );

$woocommerce->put( 'products/124/variations/125', [ 'regular_price' => '59.00', 'stock_quantity' => 3 ] );

$data = [
	'sku'            => 'HP-KN-MERINO-GRY-L',
	'regular_price'  => '65.00',
	'manage_stock'   => true,
	'stock_quantity' => 11,
	'attributes'     => [ [ 'id' => 1, 'option' => 'Gray' ], [ 'id' => 2, 'option' => 'L' ] ]
];
$woocommerce->post( 'products/124/variations', $data );

Stock is shared by all languages. A stock value written to any language becomes the stock of every language.

Prices in Secondary Currencies

Use the custom_prices parameter to set a product’s prices in your store’s secondary currencies:

  1. Turn on multicurrency. Go to WPMLSettingsMulticurrency, tick Enable the multicurrency mode and click Save changes. Under Show currencies based on, choose an option (for example Site Language) and click Save changes. Then add each currency with Add currency.
  2. Send the prices to the original product, with your store’s currency codes. WPML stores the prices of the store’s currencies, and every language shows them.
    Set prices in a secondary currencyPHP
    $data = [
    	'custom_prices' => [
    		'USD' => [ 'regular_price' => '55.00', 'sale_price' => '49.00' ]
    	]
    ];
    $woocommerce->put( 'products/14', $data );
  3. For a variable product, send the prices on each variation, not on the parent product.
    Set a variation’s price in a secondary currencyPHP
    $data = [
    	'custom_prices' => [
    		'USD' => [ 'regular_price' => '48.00' ]
    	]
    ];
    $woocommerce->put( 'products/80/variations/81', $data );
  4. Read the stored prices from meta_data in the product or variation answer: _regular_price_USD, _sale_price_USD and _price_USD for US dollars.

Create an Order


Adding a lang parameter will set the specified language for the specified order. The emails that the customer receives for the order are sent in that language too.

Please note that the products, if added in a different language than the one provided as an argument here, will not be converted automatically but instead be added in their language.

Example:

Create an orderPHP
$data = [
    'payment_method' => 'bacs',
    'payment_method_title' => 'Direct Bank Transfer',
    'set_paid' => true,
    'billing' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'address_1' => '969 Market',
        'address_2' => '',
        'city' => 'San Francisco',
        'state' => 'CA',
        'postcode' => '94103',
        'country' => 'US',
        'email' => 'john.doe@example.com',
        'phone' => '(555) 555-5555'
    ],
    'shipping' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'address_1' => '969 Market',
        'address_2' => '',
        'city' => 'San Francisco',
        'state' => 'CA',
        'postcode' => '94103',
        'country' => 'US'
    ],
    'customer_id' => 2,
    'line_items' => [
        [
            'product_id' => 58,
            'quantity' => 2
        ],
    ],
    'shipping_lines' => [
        [
            'method_id' => 'flat_rate',
            'method_title' => 'Flat Rate',
            'total' => '10.00'
        ]
    ],
    'lang' => 'el',
    'currency' => 'USD'
];
$order = $woocommerce->post('orders', $data );

Related WooCommerce Documentation: Create an order (opens in a new tab)

Creating Taxonomy Terms (Product Category, Tag, Attribute, Shipping Class)

Please note that you can use the REST API to translate Attribute terms (e.g. Blue), but not Attribute names (e.g. Color). To translate Attribute names, go to WPMLTaxonomy Translation, choose the attribute from the dropdown menu, and add translations under the Translations of taxonomy labels and slug section.

Two parameters are supported when creating a term:
  • lang – the respective lang value will be set for the term. If omitted, the default language of the site will be used.
  • translation_of (optional) – the term will be created as a translation of an existing term, having the id provided by the value of translation_of. If translation_of is omitted, the term is created as part of a new translation group (trid)

Example: Create a category in the second language, as a translation of the category with the ID 32.
Create CategoryPHP
$category = [ 'name' => 'Wohnen und Geschenke', 'slug' => 'wohnen-und-geschenke', 'lang' => 'de', 'translation_of' => 32 ];
$woocommerce->post( 'products/categories', $category );

Related WooCommerce Documentation: Create a product category (opens in a new tab)

Example: Translate a global attribute term into the secondary languages. Here the attribute (Color) has the ID 1 and the original term (Gray) has the ID 56.

Translate Global Attribute TermPHP
$data = [
	'create' => [
		[ 'name' => 'Grau', 'slug' => 'grau', 'lang' => 'de', 'translation_of' => 56 ],
		[ 'name' => 'Gris', 'slug' => 'gris', 'lang' => 'fr', 'translation_of' => 56 ]
	]
];
$woocommerce->post( 'products/attributes/1/terms/batch', $data );

Related WooCommerce Documentation: Create an attribute term (opens in a new tab)

Errors

When a request cannot be applied, WPML Multilingual & Multicurrency for WooCommerce answers with one of these errors. The message is in the language of the request, so check the HTTP status and not the text:

AnswerWhenWhat to do
HTTP 422 Invalid language parameterThe lang value is not one of the site’s active languages: when creating or updating a product.Send the code of an active language.
HTTP 400 wcml_translation_existsA product is created with translation_of in a language that already has a translation of that product. The message names the ID of the existing translation.Update the existing translation instead, with PUT products/<id>.
HTTP 422 Using "translation_of" requires providing a "lang" parameter tooA product is sent with translation_of and without lang.Send lang with every translation_of.
HTTP 422 Product not foundThe translation_of value of a product is an ID that has no language in WPML.Send the ID of the original product.

Written byAmir