ショートコードを使って、投稿の内容にJavascriptによる効果を付加するプラグインを作って使っていますが、現状では
add_action('init', 'load_jqtools_ini');
add_action('wp_head', 'start_jqtools');を使って常時ロードしている構成です。
これをショートコードが存在したときにだけ、スクリプトの類をロードさせるようにするにはどのような仕掛けを施したらよいのでしょうか。
こんな感じで、$wp_query->posts に目的のショートコードが含まれているか正規表現でチェックし、無ければ wp_enqueue_script() を呼び出さないようにしてます。
add_action('wp_print_scripts', 'add_my_scripts');
function add_my_scripts() {
if (!has_shortcode('shortcode'))
return;
wp_enqueue_script('hogehoge', 'http://example.com/fugafuga.js');
}
function has_shortcode($shortcode) {
global $wp_query;
$posts = $wp_query->posts;
$pattern = '/\[' . preg_quote($shortcode) . '[^\]]*\]/im';
$found = false;
$hasTeaser = !( is_single() || is_page() );
foreach($posts as $post) {
if (isset($post->post_content)) {
$post_content = $post->post_content;
if ( $hasTeaser && preg_match('/<!--more(.*?)?-->/', $post_content, $matches) ) {
$content = explode($matches[0], $post_content, 2);
$post_content = $content[0];
}
if ( !empty($post_content) && preg_match($pattern, $post_content) ) {
$found = true;
}
}
if ( $found )
break;
}
unset($posts);
return $found;
}
コメントを残す