Support » Alpha/Beta/RC » Issue with wp_localize_script() or similar on block themes?

  • I’m using a development version (5.9-beta4-52409).

    It looks like the wp_localize_script() isn’t working as expected on any block theme such as Twenty Twenty-Two.

    Here’s the code snippet in the theme’s functions.php

    add_action( 'wp_enqueue_scripts', function() {
    	wp_register_script( 'my-script', '', array(), '0.0.1', false );
    } );
    add_shortcode( 'my_shortcode', function() {
    	wp_enqueue_script( 'my-script' );
    			'is_okay' => 'Yes'
    	return 'Shortcode Content';
    } );

    Upon adding the shortcode and visiting the page. The script.js is enqueued, but the localization isn’t working. There’s an error “my_params” is not defined in the console.

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz


    You cannot use wp_localize_script() from within a shortcode callback. It executes at the wrong time in there. It needs to be called in the same context as the enqueued script that it’s related to. If the data you need to pass is only available to the shortcode callback, instead of wp_localize_script(), you could simply add the JS declarations within <script> tags and include them with any other returned shortcode content.

    FWIW, wp_localize_script() was not intended for use in passing random data from PHP to page scripts. It really is meant for localization and internationalization. But it served the alternative use as well, so now we see it in examples everywhere. But now there’s a more appropriate function: wp_add_inline_script(). It basically works the same way, it’s just that the function name is more appropriate for the intended use.

    Thread Starter Sanjeev Aryal


    Thank you for sharing the details.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.