[wp-trac] [WordPress Trac] #57945: Locale bug in short-circuited WP REST API request via rest_pre_dispatch?

WordPress Trac noreply at wordpress.org
Mon Mar 20 00:16:45 UTC 2023


#57945: Locale bug in short-circuited WP REST API request via rest_pre_dispatch?
--------------------------------+------------------------------
 Reporter:  joeyojoeyo12        |       Owner:  (none)
     Type:  defect (bug)        |      Status:  new
 Priority:  normal              |   Milestone:  Awaiting Review
Component:  REST API            |     Version:  6.1.1
 Severity:  normal              |  Resolution:
 Keywords:  close dev-feedback  |     Focuses:
--------------------------------+------------------------------
Changes (by joeyojoeyo12):

 * keywords:  reporter-feedback close => close dev-feedback


Comment:

 Replying to [comment:1 TimothyBlynJacobs]:
 > Hi @joeyojoeyo12,
 >
 > To handle the locale, you can set either `?_locale=user` to return the
 content in the user's locale, or `?_locale=site` to return the content in
 the site's locale.
 >
 > See #44758.


 Hi there, thanks for the fast reply.

 Adding {{{?_locale=site}}} to the REST API requests' route from the
 requesting client did not change anything in the above-mentioned
 behaviour. Please note that the locale is correct. If I echo get_locale()
 right before returning the WP_Error instance in my callback hooked onto
 rest_pre_dispatch, I get the correct locale. But the message of the
 returned WP_Error, written via __('to be translated','my'plugin'), and
 having an according translation in the plugins' mo and po files as
 mentioned above, is not returned in the requests' locale, but in the
 sites' default locale instead. Please note again that this behaviour only
 happens for requests which are short-circuited via the rest_pre_dispatch
 hook.

 My current workaround is this right before returning a {{{WP_Error}}}
 instance holding a {{{__('localized message','my-plugin')}}} as its error
 message, within a callback hooked to {{{rest_pre_dispatch}}}, for the
 error message to get displayed properly:


 {{{
 $current_locale = get_locale(); // retrieved from the client as explained
 above, so correct

 $mo = new MO();

 if ($mo->import_from_file(WP_CONTENT_DIR . "/languages/plugins/my-
 plugin-$current_locale.mo")) {
     $translations[$current_locale] = $mo->entries;
 }

 echo $translations[$current_locale]['localized message']->translations[0];
 }}}

 But this seems like a horrible hack to me..?
 [https://stackoverflow.com/questions/31778466/get-translations-for-a
 -string-in-wordpress]

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/57945#comment:4>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list