Only loads on the contact template page

In the footer i load the Google maps api. But only on the contact page, i used the google maps api. Now i want to make code. That the google maps api is only load in the contact template pages. How can i make that.

This is the script tag in the footer.

Read More
 <script type="text/javascript" src="//maps.google.com/maps/api/js?v=3&amp;sensor=false"></script>

That script tag. Must only load in the template contact page.

Thank for helping

Related posts

Leave a Reply

3 comments

  1. First a bit of advise (since the solution is based on it) – always “enqueue” your scripts, don’t just add them in the footer. Read this, for example .
    Now the solution for loading scripts on specific template, since this is what you asked for:

    function enqueue_themescrits()
    {
        if ( is_page_template('contact.php') ) { //the file your contact page uses
             wp_register_script( 'google_maps', 'http://maps.google.com/maps/api/js?v=3&amp;sensor=false' );
             wp_enqueue_script( 'google_maps' );
        }
        //Your other enqueued scripts
    
    }
    add_action( 'wp_enqueue_scripts', 'enqueue_themescrits' );
    

    EDIT: add this to your functions.php

  2. You’ve got »Conditional Tags« in WordPress. Those allow you do determine if some condition meets or not (basically those are parts of the $wp_query object, just wrapped with a public API function).

    In detail: There’s is_page(), which tells you if you’re on the desired page not.

    So just wrap it into a function, hook in at the right hook and abort if you’re not on the desired page.

    The following goes into your functions.php file (or a small custom plugin).

    /** Plugin Name: Register Google Maps Script */
    function wpse65356_enqueue_gmaps()
    {
        if ( ! is_page( 'contact' ) )
            return;
    
        wp_enqueue_script(
             'google-maps'
            ,'maps.google.com/maps/api/js?v=3&amp;sensor=false'
            ,array()
            ,0
            ,true
        );
    }
    add_action( 'wp_enqueue_scripts', 'wpse65356_enqueue_gmaps' );
    
  3. Javascript (and css) should be added with wp_enqueue_script.
    Register the script but don’t enqueue it yet in functions.php.

    Call the enqueue on the contact template page before wp_head(),
    which should be located in header.php so before get_header().

    registering and queueing is confusing at first here is a good tutorial