Polylang Language Fields in the REST API
Adds pll_language and pll_translations fields to posts and pages in the REST API, which Polylang's free version does not provide, so headless sites and apps can link translations.
Opens WPIDE on
Code
$wpide_types = array( 'post', 'page' ); // Post types to extend.
add_action( 'rest_api_init', function () use ( $wpide_types ) {
if ( ! function_exists( 'pll_get_post_language' ) ) {
return;
}
register_rest_field( $wpide_types, 'pll_language', array(
'get_callback' => function ( $post ) {
$slug = pll_get_post_language( $post['id'] );
return $slug ? array( 'slug' => $slug, 'locale' => pll_get_post_language( $post['id'], 'locale' ) ) : null;
},
'schema' => array( 'type' => array( 'object', 'null' ), 'context' => array( 'view', 'edit' ) ),
) );
register_rest_field( $wpide_types, 'pll_translations', array(
'get_callback' => function ( $post ) {
return (object) array_map( 'intval', (array) pll_get_post_translations( $post['id'] ) );
},
'schema' => array( 'type' => 'object', 'context' => array( 'view', 'edit' ) ),
) );
} );
Notes
Add custom post types to $wpide_types. The translations field maps language slugs 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.