Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce Multilingual Create Products
// Product in default language
{
global $sitepress;
$sitepress->switch_lang('en');
// Add the product (a post of type 'product')
$post_id = wp_insert_post($post_data);
// Attach media to it
set_post_thumbnail( $post_id, get_post_id_by_title( $code, 'attachment' ) );
// Update product fields
foreach ($meta_fields as $wc_key => $my_key) {
update_post_meta($post_id, $wc_key, $data[ $my_key ]);
}
// BUG: https://wordpress.org/support/topic/products-are-not-showing-on-product-category-page/#post-6996204
update_post_meta( $post_id, '_visibility', 'visible' );
update_post_meta( $post_id, '_stock_status', 'instock');
update_post_meta( $post_id, 'total_sales', '0' );
// Set category
$term = get_term_by( 'slug', $data['category'], 'product_cat' );
wp_set_object_terms( $post_id, $term->term_id, 'product_cat' );
}
// Product in other langauge:
{
// Get WPML & WooCommerce WPML
global $woocommerce_wpml, $iclTranslationManagement, $woocommerce_wpml, $sitepress, $wpdb;
$woocommerce_wpml->sync_variations_data = new WCML_Synchronize_Variations_Data($woocommerce_wpml, $sitepress, $wpdb);
$language_code = 'ar';
$sitepress->switch_lang($language_code);
// Duplicate post
$t_post_id = $iclTranslationManagement->make_duplicate($post_id, $language_code);
$tn = get_post( $t_post_id );
// Create job
$translation_editor = new WCML_Translation_Editor($woocommerce_wpml, $sitepress, $wpdb);
$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 );
$trid = $original_post_language_info->trid;
$translation_editor->create_product_translation_package( $post_id, $trid, $language_code, ICL_TM_COMPLETE );
$j = $translation_editor->create_product_translation_package( $post_id, $trid, $language_code, ICL_TM_COMPLETE );
$trans_job_id = $iclTranslationManagement->add_translation_job( $j['rid'], $j['user_id'], $j['translation_package'] );
$job_details = array('job_type' => 'wc_product',
'job_id' => $post_id,
'target' => $language_code,
'translation_complete' => ICL_TM_COMPLETE);
// Create editor
$editor = new WCML_Editor_UI_Product_Job( $job_details, $woocommerce_wpml, $sitepress, $wpdb );
// Fill up translation
$t[ md5( 'title' ) ] = $tn->post_title;
$t[ md5( 'product_content' ) ] = $tn->post_name;
$t[ md5( 'product_content' ) ] = $tn->post_excerpt;
$t[ md5( '_purchase_note' ) ] = get_post_meta( $tn->ID, '_purchase_note', true );
// Save as complete
$editor->save_translations( $t );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment