终于制定了一个粗略的工作解决方案。这可能不是最终版本,但这是我为任何可能感兴趣的人提供的解决方案。
function gotImages()
{
global $wp_query;
$posts = $wp_query->posts;
if ( empty( $posts ) )
return $posts;
$searchImages = '~<img [^>]* />~';
foreach ($posts as $post) {
$content = $post->post_content;
preg_match_all( $searchImages, $content, $countImages );
$images += count($countImages[0]);
}
return ( $images >= 1 ? true : false );
}
这个函数如果放在functions.php中,会读取当前循环的内容并扫描<IMG>标签。如果找到一个或多个标签,则返回 true,否则返回 false。
现在我可以使用它来有条件地将脚本或样式表排入队列,具体取决于帖子是否有任何图像。
例如这样:
if( !is_admin() && gotImages() == true ) :
wp_register_script('fancybox', get_stylesheet_directory_uri() . '/libs/fancybox/jquery.fancybox.pack.js', array('jquery'), false, true);
wp_register_script('fancybox.init', get_stylesheet_directory_uri() . '/js/init/lightbox.init', array('fancybox'), false, true);
wp_enqueue_script('fancybox');
wp_enqueue_script('fancybox.init');
endif;
我还不确定这个功能有多“昂贵”,但我正在开发的网站非常小,所以现在这并不是什么大问题,它会增加几毫秒的处理时间。