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 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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.