Support » Plugins » Hacks » wp_localize_script

  • Hi!

    I’m trying to get a like script running on my blog.

    This is a part of the code, which I placed in my functions.php:

    wp_localize_script('like_post', 'ajax_var', array(
    	'url' => admin_url('admin-ajax.php'),
    	'nonce' => wp_create_nonce('ajax-nonce')

    But when I run it in debug mode, the following error appears:

    wp_localize_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or init hooks.

    I’ve did many searches, but could only find solutions about “wp_enqueue_script”, but unfortunately not about “wp_localize_script”.

    So is there something I’m doing wrong what makes the error appears?

    Thanks in advance!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Perhaps
    1. you dont call localize script after enqueue
    2. check from exactly where it has been called, perhaps try to put it in a init hook.

    kind regards

    wp_localize_script, just like wp_enqueue_script and wp_register_script, should be called from within a hook.

    Usually you register you scripts on the ‘init’ hook, and enqueue them on the ‘wp_enqueue_scripts’ hook.

    Assuming ‘like_post’ is an already registered script, here is a working localization example:

    add_action('wp_enqueue_scripts', 'enqueue_theme_scripts');
    function enqueue_theme_scripts()
    	$params['url'] = admin_url('admin-ajax.php');
     	$params['nonce'] = wp_create_nonce('ajax-nonce');
    	wp_localize_script('like_post', 'ajax_var', $params);

    Hope this helps.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘wp_localize_script’ is closed to new replies.