Scripts which are very specific to shortcodes can be loaded directly inside the shortcode and do not have to be registered through the wp_enqueue_scripts
hook. This has the advantage of you do not need to run extra code and checks to load the script conditionally, so the has_shortcode()
check can be dropped. There is also nothing wrong with running inline scripts here, so feel free to use them as well
You can probably do something like this
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
add_shortcode( 'mymapshortcode2', 'do_mymapshortcode2');
function do_mymapshortcode2() {
if ( !isset($GLOBALS['wp_the_query'])
|| !is_a($GLOBALS['wp_the_query']->get_queried_object(),'WP_Post')
)
return '';
// Enqueue your custom scripts here
wp_enqueue_script( 'gmapscript2', 'http://maps.google.com/maps/api/js?sensor=false' );
// return a div for the map to be written
return "<script>/* my min js goes here */ </script>
<div id=\"themap\" style=\"width:500px; height:500px;\">
<p>Loading map...<noscript><p>Cannot show map because js is disabled</noscript></p>
</div>";
}
?>
Also, is it possible / better to move the tests for
has_shortcode
to enclose theadd_action
It is always better to run conditional checks inside your callback function due to issues you might have with a specific scope.