0

I am try to enque and localize my word-press scripts My code for for enque my scripts is

function load_my_scripts() {
    wp_register_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'));
    wp_enqueue_script('twentyfifteen-custom-js', get_template_directory_uri() . '/js/custom.js', array(), '20141010', true);
    wp_localize_script( 'custom-js', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

add_action('wp_enqueue_scripts', 'load_my_scripts');

My custom js is being enqueue if i do view source but not able to localize ajax.php.

Where i am making mistake please let me know.

1

First of all, you are NOT enqueuing the script.. Try this code, working in my test install.

function load_my_scripts() {

    // Create the localizations array
    $localize = array( 
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
    );

    // Register The Script First
    wp_register_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'));

    wp_enqueue_script('twentyfifteen-custom-js', get_template_directory_uri() . '/js/custom.js', array(), '20141010', true);

    // Register the localization
    wp_localize_script( 'custom-js', 'MyAjax', $localize );

    // Enqueue the script
    wp_enqueue_script( 'custom-js' );
}

add_action('wp_enqueue_scripts', 'load_my_scripts');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.