Reputation: 1985
I want to insert a piece of javascript to Wordpress post page, What is the best way to insert this code?
<style type="text/css">
#map-canvas { height: 100%; margin: 0; padding: 0;}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=api">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: { lat: -34.397, lng: 150.644},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas"></div>
How can I HARDCODE THIS? how to insert div elements correctly to my post?
Upvotes: 0
Views: 2755
Reputation: 2359
The best way would be using wp_enqueue_script and wp_register_script functions to include the javascript files using the wp_enqueue_Scripts hook
I would do the following:
in your functions.php:
add_action( 'wp_enqueue_scripts', 'add_my_scripts' );
function add_my_scripts(){
// register the scripts
wp_register_script( 'gmap', 'https://maps.googleapis.com/maps/api/js?key=api' );
wp_register_script( 'theme-js', get_stylesheet_directory_uri() . '/js/my-script.js', array('gmap') );
// enqueue only if needed
if( is_page('your-map-page') ) {
wp_enqueue_script('gmap');
wp_enqueue_script('theme-js');
}
}
// register a shortcode to use like [google-map]
add_shortcode('google-map', 'google_map_func');
function google_map_func() {
return '<div id="map-canvas" style="height: 100%; margin: 0;padding: 0;"></div>';
}
In your my-script.js:
function initialize() {
var mapOptions = {
center: { lat: -34.397, lng: 150.644},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
Upvotes: 1