短代码是 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’);
以此类推,也可以加载特定的样式。