lloc / Multisite-Language-Switcher

WordPress Plugin: Multisite Language Switcher
http://msls.co
129 stars 40 forks source link

Get translations when calling Wordpress Rest API #232

Open lucky-yoolk opened 1 year ago

lucky-yoolk commented 1 year ago

hi,

first thanks for your awesome plugin! Saves me a lot of time when i have to manage Multilingual websites.

Is there a way to register translations when calling Wordpress Rest API?

Below is my attempt at doing something beyond my expertise ^^

/* https://domain.com/en/wp-json/wp/v2/post/id */
function register_mls_for_rest_api() {
    register_rest_field( 
        'post',
        'mls_translations',
        array(
            'get_callback'    => 'get_mls_translations',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}
add_action( 'rest_api_init', 'register_mls_for_rest_api' );

function get_mls_translations() $object, $field_name, $request ) {
    // this is where i'm stuck...
    // $lang_array      = where_im_stuck('-_-');
    // $hreflang        = $lang_array['0'];
    // $href        = $lang_array['1'];
    // return array(
    //  $hreflang => $href,
    // );
}
lloc commented 11 months ago

Hey looks good. I guess you should return the values using rest_ensure_response(). What are the values that you want to have in $lang_array?

$blog     = MslsBlogCollection::instance()->get_current_blog();
$language = $blog->get_language(); // en_US
$alpha2   = $blog->get_alpha2(); // en

or

$arr = [];
foreach ( MslsBlogCollection::instance()->get() as $blog ) {
    $arr[] =  $blog->get_language();
}

?

Read on here: https://msls.co/developer-docs/snippets-examples/