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

WordPress Trac noreply at wordpress.org
Sun Mar 19 06:07:50 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:  critical      |   Keywords:
  Focuses:                |
--------------------------+-----------------------------
 To reproduce the issue: you may register a custom REST endpoint using
 {{{register_rest_route}}} in your main plugin file of your custom plugin.
 That endpoint simply produces a response via localization, via a {{{__
 ('sample-string','my-plugin')}}} call and the according {{{.mo/.po}}}
 files within {{{plugins/my-plugin/languages}}}, as well as in
 {{{languages/plugins/..}}} (tested both to be sure).

 Next, access your frontend, without being logged in into the admin, in a
 language which is not the default of the page, e.g. by creating two
 translations of a page via Polylang. Fire a REST API request to your
 custom endpoint. {{{__('sample-string','my-plugin')}}} is returned back to
 the frontend in the site's default language, and not in the (non-default)
 language of the page.

 As a workaround for this, I:
 - send a custom HTTP header along with every WP REST request (e.g. X-MYP-
 LANG)
 - created custom callback in main plugin file, hooked onto init hook, to
 get its value and then {{{switch_to_locale}}} accordingly.

 - result: correct translation of {{{__('sample-string','my-plugin')}}} is
 now output.

 PROBLEM:
 Whenever I short-circuit a custom REST request's response via
 {{{rest_pre_dispatch}}}, this stops working. You may return a
 {{{WP_Error}}} via the {{{rest_pre_dispatch}}} hook for any incoming
 request to your custom endpoint. The message of that {{{WP_Error}}} being
 a localization, e.g. {{{__('error message','my-plugin')}}}, it is returned
 back in the default language, no matter if I
 {{{switch_to_locale('target_language')}}} explicitly right before
 returning the {{{WP_Error}}}, reload the plugin textdomain via
 {{{load_plugin_textdomain()}}} before doing so, or both. Bug?

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


More information about the wp-trac mailing list