wp_localize_script (3 posts)

  1. jasonsweb
    Posted 3 years ago #


    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!

  2. carl_erikl@hotmail.com
    Posted 2 years ago #

    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

  3. Anastis Sourgoutsidis
    Posted 2 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic