WordPress: creare uno shortcode per le Google Maps con il plugin jQuery Gmap3

WordPress: creare uno shortcode per le Google Maps con il plugin jQuery Gmap3

In questo articolo vedremo come implementare in WordPress uno shortcode per le Google Maps che ci permetta di specificare le nostre coordinate utilizzando il plugin jQuery Gmap3.

Per prima cosa definiamo in functions.php il nostro shortcode ed includiamo gli script solo se tale shortcode è presente nelle pagine o nei post:

 
function my_google_maps_shortcode( $atts ) {
	extract( shortcode_atts( array(
		'lat' => '',
		'long' => ''
	), $atts ) );
	
	$html = '<div class="my-google-maps" data-lat="' . $lat . '" data-long="' . $long . '"></div>';
	
	return $html;

}

add_shortcode( 'my-google-maps', 'my_google_maps_shortcode' );

function my_google_maps_scripts() {
	global $post;
	$content = $post->post_content;
	
	if( has_shortcode( $content, 'my-google-maps' ) ) {
		wp_register_script( 'google-maps', 'http://maps.google.com/maps/api/js?sensor=false' );
		wp_enqueue_script( 'google-maps' );
		wp_register_script( 'gmap3', get_template_directory_uri() . '/js/gmap3.min.js', array( 'jquery' ), false );
		wp_enqueue_script( 'gmap3' );
		wp_register_script( 'gmap3-loader', get_template_directory_uri() . '/js/gmap3-loader.js', array( 'gmap3' ), false );
		wp_enqueue_script( 'gmap3-loader' );
	}

}

add_action( 'wp_enqueue_scripts', 'my_google_maps_scripts' );

Lo shortcode può essere utilizzato in questo modo:


[my-google-maps lat="46.578498" long="2.457275"]

Quindi definiamo gli stili CSS per le mappe (le dimensioni sono necessarie):


.my-google-maps {
	width: 100%;
	height: 400px;
}

Infine creiamo il file gmap3-loader.js con questo codice:


(function( $ ) {
	$(function() {
		$( "div.my-google-maps" ).each(function() {
			var $map = $( this );
			var lat = $map.data( "lat" );
			var lon = $map.data( "long" );
			
			var options = {};
			options.center = [ lat, lon ];
			options.zoom = 5;
			options.mapTypeId = google.maps.MapTypeId.ROADMAP;
			
			$map.gmap3({
				map: {
					options: options
				}
			});
		});
	
	});

})( jQuery );

Torna su