判断 WordPress 文章中有特定短代码时加载脚本

WordPress2333阅读模式

短代码是WordPress常用的功能,虽然目前已被区块所取代,但还是普遍应用中。有些短代码会用到JS脚本,但又不想全局加载,可以用下面的代码实现,添加短代码时仅在当前页面加载JS脚本。

判断 WordPress 文章中有特定短代码时加载脚本

判断 WordPress 文章中有特定短代码时加载脚本

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');

以此类推,也可以加载特定的样式。

 

 

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  2  访客  2
    • 格子老师
      格子老师 1

      学习了!!

      • 大致
        大致 0

        有点草率了,换成preg_match更好吧,毕竟很多短代码带参数的。

      匿名

      发表评论

      匿名网友
      :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

      拖动滑块以完成验证