垃圾站 WP教程 判断WordPress文章中有特定短代码时加载脚本

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

短代码是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');

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

上一篇
下一篇
联系我们

联系我们

返回顶部