Hasan
Hasan

Reputation: 909

Adding javascript file to a wordpress page

I want to add a JavaScript file containing my codes for displaying a Google map application in a WordPress page. In the page I just have a "div" tag which will accommodate the Google Map. How can I link the .js file in the page? Also what will be the best location to place the folder in my server containing the .js file?

Thanks in advance for your answer!

Upvotes: 0

Views: 394

Answers (2)

Domain
Domain

Reputation: 11808

on your sever you will must be having a folder with all the wordpress files. In those files you will find folders wp-content > themes > (current theme you are using on the WordPress). Open this folder containing the theme files. Here create a folder to place all your js files. If a folder for js already exists use that one. Now add your js file in that folder. In the folder containing all your theme files you will find a file 'functions.php'. Open this file and add the following code.

add_action( 'wp_enqueue_scripts', 'maps_load_scripts');
function maps_load_scripts(){
  wp_enqueue_script( 'google-maps-js', get_stylesheet_directory_uri().'/(name-of-folder-  containing-all-js-files)/(name-of-your-js-file).js', array('jquery'), '1.0', false);
} 

This will load your js file on all the pages. If you want to load the js file on a particular page then all the above code in the condition:

add_action('template_redirect', 'load_js_certain_page');
function load_js_certain_page(){
$page_id = ;// Use the id of the page in WordPress here. You can find the page id from the database or the WordPress backend.
if(is_page($page_id)){
//add the code from the block above here. 
}
}

Upvotes: 1

Thaveedu
Thaveedu

Reputation: 131

First of all , i like to clarify your question a little bit . Do you want the code to be part of a single page or part of the whole template/layout ?

If you want that to be part of a single page/post please refer the below tutorial: http://www.tipsandtricks-hq.com/how-to-add-javascript-in-a-wordpress-post-or-page-1845

Or else if you need it to be part of the whole layout , you should consider making a widget and make changes to the template to accommodate that in place.For making a widget refer this document. http://codex.wordpress.org/Widgets_API

Upvotes: 0

Related Questions