# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Multilingual](https://wpide.com/library/category/multilingual/)
- Tags: wpml, rest-api, headless
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/wpml-rest-language-fields/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add Language and Translations to the REST API (WPML)" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
