forked from maru3l/wp-rest-polylang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wp-rest-polylang.php
93 lines (73 loc) · 2 KB
/
wp-rest-polylang.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
/**
* Plugin Name: WP REST - Polylang - Stylers
* Description: Polylang integration for the WP REST API
* Author: Marc-Antoine Ruel
* Author URI: https://www.marcantoineruel.com
* Version: 1.0.1
* Plugin URI: https://github.com/stylers-llc/wp-rest-polylang
* License: gpl-3.0
*/
class WP_REST_polylang
{
static $instance = false;
private function __construct() {
// Check if polylang is installed
require_once ABSPATH . 'wp-admin/includes/plugin.php';
if (!is_plugin_active('polylang/polylang.php')) {
return;
}
add_action('rest_api_init', array($this, 'init'), 0);
}
public static function getInstance() {
if ( !self::$instance )
self::$instance = new self;
return self::$instance;
}
public function init() {
global $polylang;
if (isset($_GET['lang'])) {
$current_lang = $_GET['lang'];
$polylang->curlang = $polylang->model->get_language($current_lang);
}
$post_types = get_post_types( array( 'public' => true ), 'names' );
foreach( $post_types as $post_type ) {
if (pll_is_translated_post_type( $post_type )) {
$this->register_api_field($post_type);
}
}
}
public function register_api_field($post_type) {
register_rest_field(
$post_type,
"polylang_current_lang",
array(
"get_callback" => array( $this, "get_current_lang" ),
"schema" => null
)
);
register_rest_field(
$post_type,
"polylang_translations",
array(
"get_callback" => array( $this, "get_translations" ),
"schema" => null
)
);
}
public function get_current_lang( $object ) {
return pll_get_post_language($object['id'], 'locale');
}
public function get_translations( $object ) {
$translations = pll_get_post_translations($object['id']);
return array_reduce($translations, function ($carry, $translation) {
$item = array(
'locale' => pll_get_post_language($translation, 'locale'),
'id' => $translation
);
array_push($carry, $item);
return $carry;
}, array());
}
}
$WP_REST_polylang = WP_REST_polylang::getInstance();