phpwordpresswoocommercewpml

Creating multilingual products with WPML


I'm creating multiple woocommerce products programmatically. In order to create translated products and according to WPML documentation i should use:

$my_translated_post = array(
        'post_title'    => $this->title_en,
        'post_content'  => $this->description_en,
        'post_status'   => $this->status,
        'post_type' => 'product', 
        'post_author'   => 1,       
    ); 
     
    $translated_post_id = wp_insert_post( $my_translated_post );
    
    $wpml_element_type = apply_filters( 'wpml_element_type', 'product' );
    $get_language_args = array('element_id' => $post_id, 'element_type' => 'product' );
    $original_post_language_info = apply_filters( 'wpml_element_language_details', null, $get_language_args );
    $product = wc_get_product( $translated_post_id );      
    $set_language_args = array(
        'element_id'    => $translated_post_id,
        'element_type'  => $wpml_element_type,
        'trid'   => $original_post_language_info->trid,
        'language_code'   => 'en', //language code of secondary language
        'source_language_code' => $original_post_language_info->language_code
    );  
    do_action( 'wpml_set_element_language_details', $set_language_args );
    $product->save();

which creates the product with title and description. However in order to "sync" prices, stock, images,categories and other metadata i have to go to "products" in the dashboard click quick edit and then click update without changing anything. From what i understand there's a "trigger" somewhere in that process that "syncs" the translated product with its parent. Any clues on how can i trigger this programmatically?


Solution

  • I have found a workaround using the woocommerce API. We can use the "batch" method of the API to mass update the products. You'd need to download the api from: https://github.com/woocommerce/wc-api-php initiate the API connection:

    include_once('vendor/autoload.php');
    use Automattic\WooCommerce\Client;
    $wooapi = new Client(URL, CK, CS, ['version' => 'wc/v3','timeout' => '99999', 'verify_ssl'=> false]);
    

    Save the product ids to an array like:

    $new_products [] = $product->get_id();
    

    Fix the array and push them to the api:

    foreach ($new_products as $key => $id) {
            $data->update->$key = [ 'id' => $id ]  ;    
        }
    $wooapi->post('products/batch', $data);
    

    Important Note: out-of-the-box the API has a limit of 100 poroducts per api call. However this can be easily changed with a hook.