phpwordpresswpml

How to set pages as translations of another page with php?


I am currently creating a network of landing pages with PHP and publish them on WordPress. These pages have parent-children relationships and I add meta data before I use wp_insert_post() in order to publish them. My code works fine but the pages are being created in English which is the WP primary language. However, the site hosts 2 more languages and uses the WPML plugin for the translations. Is there any way to create the translated pages and set them as translations of the original ones by only using code?


Solution

  • Here's a sample of how to programmatically insert post and translation in PHP. Here en is default language and de is secondary language.

    It's basically:

    Sample:

    $new_page_id = wp_insert_post($new_page);
    $new_page_translated_id = wp_insert_post($new_page_translated);
    $wpml_element_type = apply_filters( 'wpml_element_type', get_post_type( $new_page_id ) );
    $wpml_element_trid   = apply_filters( 'wpml_element_trid', false, $new_page_id, $wpml_element_type );
    
    $set_language_args = array(
      'element_id'    => $new_page_translated_id,
      'element_type'  => $wpml_element_type,
      'trid'   => $wpml_element_trid,
      'language_code'   => 'de',
      'source_language_code' => 'en',
    );
    
    do_action( 'wpml_set_element_language_details', $set_language_args );