Skip to content

Instantly share code, notes, and snippets.

@them-es
Last active September 26, 2023 09:52
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save them-es/3ab1aa674fdb1829a3079f09559c8614 to your computer and use it in GitHub Desktop.
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.
<?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 );
}
@mustafakucuk
Copy link

Simple codes for all post types


add_action('rest_api_init', function () {
    foreach (get_post_types(array('show_in_rest' => true), 'objects') as $post_type) {
        add_filter('rest_' . $post_type->name . '_query', 'wp_rest_filter_add_filter_param', 10, 2);
    }
});

function wp_rest_filter_add_filter_param($args, $request)
{
    $lang = $request->get_param('lang');


    if (!$lang) {
        return $args;
    }

    $args['lang'] = $lang;

    return $args;
}

@rosa2
Copy link

rosa2 commented Oct 2, 2022

@everdha thanks.
@mustafakucuk your code didn't work in functions.php

have a good day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment