• Resolved Lukasz

    (@wpfed)


    I have a contact form that uses WP REST api, I return custom json response + using WP string translation function __()

    $response = array(
     'status'     => 'mailsent',
     'message'    => array(),
     'pg_message' => __( 'One or more fields have an error. Please verify your entries and try again.', 'theme' ),
    );

    I am expecting French locale but I get the default wp-admin locale returned instead(en_CA).

    Forcing switch_to_locale(‘fr_CA’) function in functions.php I can get french translation to work but looking for a proper solution to this.

    Thanks!

    • This topic was modified 5 years, 1 month ago by t-p. Reason: Moved to Fixing WordPress. This is not a Developing with WordPress topic
Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    The API uses whatever language is set in admin. This can be altered through the “locale” filter. If you are just going to always force “fr_CA”, why not set your admin language accordingly?

    By using the “locale” filter, you can dynamically assign language based on some other criteria like a user meta value or cookie.

    Thread Starter Lukasz

    (@wpfed)

    Thank you @bcworkz ! I used hidden input field in form with value of current locale.

    /**
         * Override WP install locale
         *
         * @param string $locale Current locale.
         *
         * @return string French (en_CA) locale if $_POST['cf_locale'] === 'fr_CA', 
         * configured locale otherwise.
    */
        function force_alternate_local( $locale ) {
            // Form hidden input
            if ( $_POST['cf_locale'] === 'fr_CA' ) {
                $locale = 'fr_CA';
    		}
    		else{
    			$locale = 'en_CA';
    		}
     
            return $locale;
        }
     
        add_filter( 'locale', 'force_alternate_local', 1, 1 );

    Sorry about the confusion with forcing switch_to_locale, was just trying to show that it is possible to get alternative language loaded but I didn;t want it forced permanently.

    • This reply was modified 5 years, 1 month ago by Lukasz.
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘WordPress REST API – returning incorrect locale’ is closed to new replies.