1

Iam having problems enqueueing a script with wp_localize_script. I have done this several times before and I cannot see what Iam doing wrong here.

I have changed the handle of the script several times and looked at working code in other plugins, but I cannot find the error.

I register my script like this:

add_action( 'wp_enqueue_scripts', array( $this, 'frontend_enqueue' ) );
function frontend_enqueue() {
    wp_register_script( 'my-handle', plugins_url( 'js/frontend.js', __FILE__), array( 'jquery' ), '1.0.0', true);
}

I want to enqueue the script in a shortcode function:

add_shortcode( 'my_shortcode', array( $this, 'shortcode_template' ) );
function shortcode_template( $atts ) {
    ...

    // Ajax and custom scripts
    wp_localize_script('my-handle', 'ajax_actions', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    ));
    wp_enqueue_script( 'my-handle' );
    
    ...
}

The file frontend.js get enqueued but I always get "not defined" error. The error is pointing to this line:

var ajaxUrl = ajax_actions.ajaxurl;

jquery.min.js?ver=3.7.1:2 jQuery.Deferred exception: ajax_actions is not defined
2
  • 1
    See wordpress.stackexchange.com/questions/277526/… Commented Jul 30, 2024 at 16:47
  • So this answer points to the $in_footer parameter, but Iam already using in footer true with wp_register_script. Maybe Iam not understanding correctly? Commented Aug 1, 2024 at 7:37

1 Answer 1

0

I think it's because you're doing your localization in the shortcode which may be messing with the order of things.

Instead do this:

add_action( 'wp_enqueue_scripts', array( $this, 'frontend_enqueue' ) );
function frontend_enqueue() {
    wp_register_script( 'my-handle', plugins_url( 'js/frontend.js', __FILE__), array( 'jquery' ), '1.0.0', true);
    wp_localize_script('my-handle', 'ajax_actions', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    ));
}

Then...

add_shortcode( 'my_shortcode', array( $this, 'shortcode_template' ) );
function shortcode_template( $atts ) {
    ...

    // Ajax and custom scripts
    wp_enqueue_script( 'my-handle' );
    
    ...
}

I think the script is being registered and the enqueuing fires when your shortcode loads but the script was already registered so the localization isn't present and that means the enqueued script doesn't have the object. I've never seen the localization done during output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.