Wordpress-检查循环是否包含带有附件的帖子


Wordpress - check if loop contains posts with attachments?

在Wordpress中,我试图将jQuery库的脚本排队,只用于有附件的帖子。

我得到了一个适用于单个帖子的简单功能:

function gotImages()
{
    $attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') );
    return ( !empty($attachments) ? true : false );
}

当我在functions.php中调用gotImages()时,对于带有附件的单个帖子,它会返回true,而对于带有多个帖子的主页,如果第一个帖子没有附件,则返回false。

我如何修改它,使其适用于多个帖子,即在我显示10个帖子的主页上?

谢谢!

如果您在主页上显示十篇帖子中的每一篇时都处于循环中,那么按原样调用它应该会产生所需的结果。它是否适用于多个帖子取决于你用来运行幻灯片的css选择器。如果您使用的是CSS id,那么您的HTML将无效,因为您将有多个具有相同id的元素。

最终得出了一个粗略的可行解决方案。这可能不是最终版本,但这是我为任何可能感兴趣的人提供的解决方案。

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;

我还不确定这个功能有多"贵",但我正在开发的网站很小,所以目前还没什么大不了的,它增加了几毫秒的处理时间。