百度 | 神马 | 搜狗 | 技术文档 | 学习资料分享 - 记录帝国CMS及运维技术的点点滴滴
你的位置:首页 > 实用IT技术 » 正文

【Wordpress相关】WordPress 技巧:只有指定的 Shortcode 存在时才载入相关脚本文件

发布时间:2020-09-17

作品分类:Wordpress相关  载入  指定  函数  时才  脚本  载入  指定  技巧

WordPress 技巧:只有指定的 Shortcode 存在时才载入相关脚本文件,

版本增加了一个新的函数 ,这个函数的主要功能就是检测指定内容里是否存在指定的 Shortcode 使用,带来的好处就是只在有使用指定 Shortcode 的文章页面才载入相关脚本文件,这样细微纠结虽然不能给页面载入带来可见的载入速度提升,但锱铢必较向来是我的癖好,好的习惯总能带来不错的效果的。

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>

可以点击 查看函数的详细介绍,这里着重讲解下使用方法,把下面的代码插入 functions.php 文件里即可

function wpjam_shortcode_scripts(){
  global $post;
  if( has_shortcode( $post->post_content, 'your-shortcode') ){
    wp_enqueue_script( 'whatever');//检测到有使用短码后需要做的事,大家随意
  }
}
add_action( 'wp_enqueue_scripts', 'wpjam_shortcode_scripts');

但是并不是每个人的网站都是使用的3.6版本,为了安全起见,修改代码如下

function wpjam_shortcode_scripts(){
  global $post;
  if( function_exists('has_shortcode') AND has_shortcode( $post->post_content, 'your-shortcode') ){
    wp_enqueue_script( 'whatever');
  }else{
    wp_enqueue_script( 'whatever');
  }
}
add_action( 'wp_enqueue_scripts', 'wpjam_shortcode_scripts');

本站推荐使用的主机:,国外主机建议使用

Top