结合使用HeadMedic的答案和get\\u shortcode\\u regex()documentation (实际上没有找到我的短代码),我创建了一个简单的函数,用于将多个短代码的脚本排队。由于短代码中的wp\\u enqueue\\u script()只会添加到页脚,这会很有帮助,因为它可以处理页眉和页脚脚本。
function add_shortcode_scripts() {
global $wp_query;
$posts = $wp_query->posts;
$scripts = array(
array(
\'handle\' => \'map\',
\'src\' => \'http://maps.googleapis.com/maps/api/js?sensor=false\',
\'deps\' => \'\',
\'ver\' => \'3.0\',
\'footer\' => false
),
array(
\'handle\' => \'contact-form\',
\'src\' => get_template_directory_uri() . \'/library/js/jquery.validate.min.js\',
\'deps\' => array( \'jquery\' ),
\'ver\' => \'1.11.1\',
\'footer\' => true
)
);
foreach ( $posts as $post ) {
foreach ( $scripts as $script ) {
if ( preg_match( \'#\\[ *\' . $script[\'handle\'] . \'([^\\]])*\\]#i\', $post->post_content ) ) {
// enqueue css and/or js
if ( wp_script_is( $script[\'handle\'], \'registered\' ) ) {
return;
} else {
wp_register_script( $script[\'handle\'], $script[\'src\'], $script[\'deps\'], $script[\'ver\'], $script[\'footer\'] );
wp_enqueue_script( $script[\'handle\'] );
}
}
}
}
}
add_action( \'wp\', \'add_shortcode_scripts\' );