Last active
September 26, 2023 09:52
-
-
Save them-es/3ab1aa674fdb1829a3079f09559c8614 to your computer and use it in GitHub Desktop.
Make Polylang compatible with the WP-API. Query language specific WP-API posts via a parameter and add the post language as a new REST field.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* https://developer.wordpress.org/reference/hooks/rest_this-post_type_query | |
* | |
* Query language specific posts via "lang" parameter: /wp-json/wp/v2/posts?lang=en | |
*/ | |
function my_theme_filter_rest_post_query( $args, $request ) { | |
$lang_parameter = $request->get_param('lang'); | |
if ( isset( $lang_parameter ) ) { | |
$args['lang'] = $lang_parameter; // https://polylang.pro/doc/developpers-how-to/#query | |
} | |
return $args; | |
} | |
add_filter( 'rest_post_query', 'my_theme_filter_rest_post_query', 10, 2 ); | |
add_filter( 'rest_page_query', 'my_theme_filter_rest_post_query', 10, 2 ); | |
//add_filter( 'rest_{my_custom_posttype}_query', 'my_theme_filter_rest_post_query', 10, 2 ); // Custom posttype | |
/** | |
* https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints | |
* | |
* Register a new REST field "language" and add it to the post data | |
* | |
*/ | |
add_action( 'rest_api_init', function () { | |
register_rest_field( 'post', 'language', my_theme_register_postlanguage_function() ); | |
register_rest_field( 'page', 'language', my_theme_register_postlanguage_function() ); | |
//register_rest_field( '{my_custom_posttype}', 'language', my_theme_register_postlanguage_function() ); // Optional: Custom posttype | |
}); | |
function my_theme_register_postlanguage_function() { | |
return array( | |
'methods' => 'GET', | |
'get_callback' => 'my_theme_get_postlanguage_function', | |
'schema' => null, | |
); | |
} | |
function my_theme_get_postlanguage_function( $data ) { | |
$post_id = $data['id']; | |
return ( function_exists( 'pll_get_post_language' ) ? pll_get_post_language( $post_id ) : null ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple codes for all post types