0

I use the following script to call the maps JavaScript in the page-about.php template. But its actually not working. The scripts are executed nowhere:

// Load maps scripts
function maps_scripts()
{   
    // If query if current Page is not wp-login-php or admin page
    if ( is_page_template('page-about.php') ) {
        wp_register_script('gmapsapi', 'http://maps.google.com/maps/api/js?sensor=false', array(), '1.0.0', true); 
        wp_enqueue_script('gmapsapi');

        wp_register_script('gmaps', get_template_directory_uri() . '/js/gmaps.min.js', array(), '1.0.0', true); 
        wp_enqueue_script('gmaps'); 

        wp_register_script('map', get_template_directory_uri() . '/js/map.js', array(), '1.0.0', true); 
        wp_enqueue_script('map'); 
    } 
}

add_action('init', 'maps_scripts');

I also tried with is_page() but its not working. When I delete the if statements the scripts are loaded on all pages.

  • 2
    use wp_enqueue_scripts instead of init. – Sumit May 2 '16 at 8:33
5

Use wp_enqueue_scripts instead on init. This will ensure you the template is already loaded.

add_action('wp_enqueue_scripts', 'maps_scripts');

Or you try to check the template using get_page_template_slug() instead of is_page_template:

$tmp = get_page_template_slug($post_id); // provide page/post ID
if('page-about.php' == $tmp) {
    // enqueue scripts here
}

Note that you don't need to register scripts before enqueueing them. Simply pass all the parameters of wp_register_script directly to the wp_enqueue_script (see the Code Reference).

  • add_action('wp_enqueue_scripts', 'maps_scripts'); solved the problem. Thank you so much! – Peesen87 May 2 '16 at 9:22

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.