我把这个打出来了。js代码段,我想从短代码调用它:
<script src="https://www.example.com/wp-content/themes/mediso-v1-03/javascript/jquery-2.2.4.min.js"></script>
<script src="https://www.example.com/wp-content/themes/mediso-v1-03/javascript/typed.js"></script>
<script>// <![CDATA[
$(function(){ $(".element-typing").typed({ strings: ["This is my typing text"], typeSpeed: 20 }); });
// ]]></script>
<p class="element-typing"></p>
以下是我的想法:
// Add Shortcode
function custom_shortcode23() {
wp_enqueue_script(\'script-typed-jquery\', \'https://www.example.com/wp-content/themes/mediso-v1-03/jquery-2.2.4.min.js\', array(\'jquery\'));
wp_enqueue_script(\'script-typed\', \'https://www.example.comwp-content/themes/mediso-v1-03/typed.js\', array(\'jquery\'));
echo \'<script>// <![CDATA[$(function(){ $(".element-typing").typed({ strings: ["This is my typing text"], typeSpeed: 20 }); });\',
\'// ]]></script>\',
\'<p class="element-typing"></p>\';
}
add_shortcode( \'typed23\', \'custom_shortcode23\' );
但它不起作用。我错在哪里?
SO网友:cjbj
首先,在jquery已经加载的情况下,您似乎正在尝试将jquery的2.2.4版排队。这看起来不太好。
其次,您不能只在短代码中回显脚本。必须使用将其添加到另一个脚本wp_add_inline_script
. 像这样:
function wpse238227_custom_shortcode23() {
wp_enqueue_script(\'script-typed\', \'https://www.example.comwp-content/themes/mediso-v1-03/typed.js\', array(\'jquery\'));
// script needs to be added
$script_to_add = \'jQuery(function ($) { $(".element-typing").typed({ strings: ["This is my typing text"], typeSpeed: 20 }); });\';
wp_add_inline_script (\'script-typed\', $script_to_add);
// the html needs to be returned
return "<p class=\'element-typing\'></p>";
}
add_shortcode( \'typed23\', \'wpse238227_custom_shortcode23\' );
请注意,此脚本将添加到页脚,因为在WordPress评估内容中的短代码时,站点的头部已经组装好了。您可能还想阅读
more about enqueueing scripts from shortcodes 一般来说