Halloween Sale 15% off Ends in See the plans
PHP

Add Language and Translations to the REST API (WPML)

Adds wpml_language and wpml_translations fields to posts and pages in the REST API, so headless front ends and apps know each item's language and the IDs of its translations.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_types = array( 'post', 'page' ); // Post types to extend.

add_action( 'rest_api_init', function () use ( $wpide_types ) {
    if ( ! defined( 'ICL_SITEPRESS_VERSION' ) ) {
        return;
    }

    register_rest_field( $wpide_types, 'wpml_language', array(
        'get_callback' => function ( $post ) {
            $details = apply_filters( 'wpml_post_language_details', null, $post['id'] );
            return is_array( $details ) ? array( 'code' => $details['language_code'], 'locale' => $details['locale'] ) : null;
        },
        'schema'       => array( 'type' => array( 'object', 'null' ), 'context' => array( 'view', 'edit' ) ),
    ) );

    register_rest_field( $wpide_types, 'wpml_translations', array(
        'get_callback' => function ( $post ) {
            $type = apply_filters( 'wpml_element_type', $post['type'] );
            $trid = apply_filters( 'wpml_element_trid', null, $post['id'], $type );
            $out  = array();
            if ( $trid ) {
                foreach ( (array) apply_filters( 'wpml_get_element_translations', null, $trid, $type ) as $code => $item ) {
                    if ( isset( $item->element_id ) ) {
                        $out[ $code ] = (int) $item->element_id;
                    }
                }
            }
            return (object) $out;
        },
        'schema'       => array( 'type' => 'object', 'context' => array( 'view', 'edit' ) ),
    ) );
} );

Notes

Add custom post types to $wpide_types. The translations field maps language codes to post IDs.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.