[wp-trac] [WordPress Trac] #63427: User roles property should always be an array, but they sometimes become an object in localized data

WordPress Trac noreply at wordpress.org
Sat May 10 06:46:35 UTC 2025


#63427: User roles property should always be an array, but they sometimes become an
object in localized data
----------------------------+-----------------------------
 Reporter:  haruncpi        |      Owner:  haruncpi
     Type:  defect (bug)    |     Status:  assigned
 Priority:  normal          |  Milestone:  Awaiting Review
Component:  General         |    Version:  6.8
 Severity:  normal          |   Keywords:  has-patch
  Focuses:  sustainability  |
----------------------------+-----------------------------
 When filtering roles via `array_filter()` in `wp-includes/class-wp-
 user.php`, the resulting array (`$this->roles`) can retain non-sequential
 numeric keys, if any roles are filtered out. This causes `WP_User->roles`
 to be treated as an object when JSON-encoded (e.g., in
 `wp_localize_script()`), instead of a proper array, which breaks client-
 side expectations.


 {{{
 $current_user = wp_get_current_user();

 $local_data = array(
     'current_user' => array(
         'id' => $current_user->ID,
         'roles' => $current_user->roles,
     ),
 );

 wp_localize_script( 'myplugin-frontend', '_myplugin_object', $local_data
 );
 }}}

 If roles contains keys like `[0 => 'editor', 2 => 'seo']` , the resulting
 JSON becomes:

 {{{
 { roles: { "0": "editor", "2": "custom" } }
 }}}

 Instead of

 {{{
 { roles: ["editor", "custom"] }
 }}}

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


More information about the wp-trac mailing list