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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.