Posted: 29 June 2014, Category: WordPress
Are you developing websites using very popular WordPress content management system?
If so you might be having a page with certain template which has specific style pulled from specific stylesheet or script.
In this post I will show you a bit of code which will include Google map scripts on certain templates such as contact-page-template.php
Let's say we have file called contact-page-template.php which contains Google map and we want all script related to google map to be loaded only with this template and no other.
In order to get google map working we need to implement following:
I will strip all code from templates as much as possible to keep this post easy to understand and avoid confusion.
Code for contact-page-template.php
<?php /* Template Name: Contact page template */ ?> <?php get_header(); ?> <article> <h1><?php the_title(); ?></h1> <div id="map-canvas"> <!-- google map here --> </div> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> </article> <?php get_footer(); ?>
Code above starts by identifying template name in my case Contact page template. It also contains div tag with id="map-canvas" and get_footer(); function which will include footer.php file with all its code and other WordPress code which I'm not going to explain here as I would like to stay focused on post topic.
Code for footer.php
File called footer.php contains footer element, link to script.js file which is located inside js folder and custom function which tells WordPress to load Google map script only if file called contact-page-template.php is loaded.
TIP: I always keeps all style links between head tags and script links before closing body tag as this is proven to improve overall site speed.
Please feel free to contact me if you have any questions, comments or suggestions.