我不确定是否在页面中正确“插入”了脚本。
具体示例:我需要使用google API生成一个地图,并决定编写一个插件来实现这一点。现在的问题是如何正确处理插入临时票据。
第一次尝试,我的插件文件使用add_shortcode
附加一个只返回<script type=\\"text/javascript\\" src=\\"...
在页面/帖子的中间。这是可行的,但我知道最好将脚本放在hearder/footer中,我应该只在需要时将它们排队。
这是我的第二次尝试:
<?php
if ( ! defined( \'ABSPATH\' ) ) exit;
add_action( \'wp_enqueue_scripts\', \'my_enqueue_scripts\' );
add_shortcode( \'mymapshortcode\', \'do_mymapshortcode\');
function my_enqueue_scripts() {
// enqueue scripts if main query is for a page or post that has the shortcode
if ( isset($GLOBALS[\'wp_the_query\'])
&& is_a($GLOBALS[\'wp_the_query\']->get_queried_object(),\'WP_Post\')
&& has_shortcode($GLOBALS[\'wp_the_query\']->get_queried_object()->post_content, \'mymapshortcode\') ){
$target=plugin_dir_url( __FILE__ ) . \'mymapshortcode.js\';
wp_enqueue_script(\'gmapscript\',\'http://maps.google.com/maps/api/js?sensor=false\');
wp_enqueue_script(\'mygmapscript\',$target,false,null,false);
}
}
function do_mymapshortcode() {
// retrun a div for the map to be written
return "<div id=\\"themap\\" style=\\"width:500px; height:500px;\\">
<p>Loading map...</p><noscript><p>Cannot show map because js is disabled</p></noscript>
</div>";
}
?>
然后,如果我决定内联我的脚本(太小了,不值得从单独的文件中获取它的开销),我会这样做:
<?php
if ( ! defined( \'ABSPATH\' ) ) exit;
add_action( \'wp_enqueue_scripts\', \'my_enqueue_scripts2\' );
add_action( \'wp_head\', \'my_wp_head2\' );
add_shortcode( \'mymapshortcode2\', \'do_mymapshortcode2\');
function my_wp_head2() {
// echo inline script if main query is for a page or post that has the shortcode
if ( isset($GLOBALS[\'wp_the_query\'])
&& is_a($GLOBALS[\'wp_the_query\']->get_queried_object(),\'WP_Post\')
&& has_shortcode($GLOBALS[\'wp_the_query\']->get_queried_object()->post_content, \'mymapshortcode2\') ){
$output= <<<\'EOT\'
<script>/* my min js goes here */ </script>
EOT;
echo $output;
}
}
function my_enqueue_scripts2() {
// enqueue script if main query is for a page or post that has the shortcode
if ( isset($GLOBALS[\'wp_the_query\'])
&& is_a($GLOBALS[\'wp_the_query\']->get_queried_object(),\'WP_Post\')
&& has_shortcode($GLOBALS[\'wp_the_query\']->get_queried_object()->post_content, \'mymapshortcode2\') ){
wp_enqueue_script(\'gmapscript2\',\'http://maps.google.com/maps/api/js?sensor=false\');
}
}
function do_mymapshortcode2() {
// retrun a div for the map to be written
return "<div id=\\"themap\\" style=\\"width:500px; height:500px;\\">
<p>Loading map...<noscript><p>Cannot show map because js is disabled</noscript></p>
</div>";
}
?>
Is it how it is supposed to be done or am I doing it wrong? 此外,是否可以/更好地移动测试has_shortcode
将add_action
所以它只测试一次,如下所示:
if ( isset($GLOBALS[\'wp_the_query\'])
&& is_a($GLOBALS[\'wp_the_query\']->get_queried_object(),\'WP_Post\')
&& has_shortcode($GLOBALS[\'wp_the_query\']->get_queried_object()->post_content, \'mymapshortcode\') ){
add_action( \'wp_enqueue_scripts\', \'my_enqueue_scripts2\' );
add_action( \'wp_head\', \'my_wp_head2\' );
}