短代码是 WordPress 常用的功能,虽然目前已被区块所取代,但还是普遍应用中。有些短代码会用到 JS 脚本,但又不想全局加载,可以用下面的代码实现,添加短代码时仅在当前页面加载 JS 脚本。
- function zm_has_shortcode( $posts ) {
- if ( empty($posts) )
- return $posts;
- $found = false;
- foreach ( $posts as $post ) {
- if ( stripos($post->post_content, ‘[my_shortcode]’) )
- $found = true;
- break;
- }
- if ( $found ) {
- wp_register_script( ‘my_script’, get_template_directory_uri() . ‘/js/my_script.js’, array(), version, false );
- wp_enqueue_script(‘my_script’);
- }
- return $posts;
- }
- add_action(‘the_posts’, ‘zm_has_shortcode’);
以此类推,也可以加载特定的样式。
文章标题:判断 WordPress 文章中有特定短代码时加载脚本
文章链接:https://www.wuyanshuo.cn/825.html
更新时间:2022年05月26日
本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn我们将第一时间处理! 资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。 所有资源仅限于参考和学习,版权归原作者所有,更多请阅读无言说网络服务协议。