Make WordPress Core

Opened 9 months ago

Closed 9 months ago

Last modified 5 months ago

#63401 closed defect (bug) (duplicate)

wp_localize_script() doesn't work with wp_register_script_module()

Reported by: mondalaci's profile mondalaci Owned by:
Milestone: Priority: normal
Severity: normal Version: 6.8
Component: Script Loader Keywords:
Focuses: Cc:

Description

Consider the following code fragment:

            wp_register_script('dummy', plugin_dir_url(__DIR__) . 'js/dummy.js', ['wp-util', 'jquery']);
            wp_localize_script('dummy', 'search', [
                'action' => 'search_knowledgebase',
                'url' => admin_url('admin-ajax.php'),
                'isAdmin' => current_user_can('administrator') || current_user_can('editor'),
                'firstName' => wp_get_current_user()->first_name,
                'email' => wp_get_current_user()->user_email,
            ]);
            wp_enqueue_script('dummy');

As expected, the following gets injected on the page:

<script type="text/javascript" id="dummy-js-extra">
/* <![CDATA[ */
var search = {"action":"search_knowledgebase","url":"http:\/\/localhost\/wordpress\/wp-admin\/admin-ajax.php","isAdmin":"1","firstName":"L\u00e1szl\u00f3","email":"laci@monda.hu"};
/* ]]> */
</script>

However, when wp_register_script_module() is used instead of wp_register_script(), the above content is not injected on the page. I'd expect it to be injected.

Change History (2)

#1 @swissspidy
9 months ago

  • Component changed from General to Script Loader
  • Milestone Awaiting Review deleted
  • Resolution set to duplicate
  • Status changed from new to closed

This is expected, because scripts ≠ modules.

I18N for modules is still missing and is tracked in #60234.

#2 @jonsurrell
5 months ago

In order to pass data to modules, a filter was introduced in WordPress 6.7:

https://make.wordpress.org/core/2024/10/14/updates-to-script-modules-in-6-7/#New-data-passing-API

Note: See TracTickets for help on using tickets.