Skip to content

Instantly share code, notes, and snippets.

@Dinamiko
Last active May 6, 2017 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dinamiko/da3c4fca67e14ab2fd1c063e4cddbc5a to your computer and use it in GitHub Desktop.
Save Dinamiko/da3c4fca67e14ab2fd1c063e4cddbc5a to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: MultilingualPress REST API Extension
* Description: Adds REST endpoints that allow users to get translations for a specific post or term.
* Version: 0.1
*/
class MLP_REST_API_Extension {
public function __construct() {
add_action( 'rest_api_init', array( $this, 'register_api_routes' ) );
}
/**
* register api routes
*/
public function register_api_routes() {
register_rest_route( 'mlp/v1', '/posts/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => array( $this, 'get_post_translations' ),
) );
}
/**
* Get post translations based on source post id
* @uses mlp_get_linked_elements in multilingual-press 2.5.4 inc / functions.php
* @uses mlp_get_blog_language in multilingual-press 2.5.4 inc / functions.php
* @param object
* @return array
*/
public function get_post_translations( $data ) {
$translations = array();
$current_blog_id = get_current_blog_id();
/*
gets an array with linked elements relation
where key is the blog id and value is the post id, example:
{
"1": 5,
"2": 7,
"4": 5
}
*/
$linked_posts = mlp_get_linked_elements( $data['id'] );
// loop through $linked_posts and populates $translations array
foreach ( $linked_posts as $key => $value ) {
switch_to_blog( $key );
$arr = array(
'blog_id' => $key,
'post_id' => $value,
'locale' => mlp_get_blog_language( $key, FALSE ),
'title' => get_the_title( $value ),
'content' => apply_filters( 'the_content', get_post_field( 'post_content', $value ) )
);
array_push( $translations, $arr );
}
switch_to_blog( $current_blog_id );
return $translations;
}
}
new MLP_REST_API_Extension();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment