Check if page/post has any anchors that link to an image jpg/gif/png

What I’m aiming to do is add fancybox to a site I’m developing, but I only want to enqueue the JS/CSS etc if the page/post needs it.

My thoughts are that I would need to check all the anchor tags on the post or page , and if the anchor tags link to any form of image (jpg, png,gif) then I will enqueue the necessary assets.

Does this seem like the correct approach? Is this a job for regex, somehow applied to a filter of the_content?

I’m ok with everything else, just need the test.

The code below adds a .fancybox class to all the anchors that link to the specified filetypes so maybe I can somehow check for the class name? PS I don’t want to use a plugin to load fancybox, prefer to do this myself.

jQuery("a[href$='.jpg'],a[href$='.png'],a[href$='.gif']").fancybox();

Update: this is a simple check that I have so far which will check the content for anchors. Just need to adapt for having a class name and I think I’m there, seems to work ok.

function content_image_check( $content ) {

if( strpos( $content, "<a" ) ) {
   echo 'yes';
} else {
   echo 'no'; 
}

return $content;
}

add_filter('the_content', 'content_image_check'); 

Update 4

I’m using a XPath query. This is the closest I’ve gotten so far. It will enqueue the css and js only if there’s anchors on the page with images inside them. I’d like to modify the query so it can find the anchors with a class of ‘fancybox’ but For some reason the query cannot see the ‘fancybox’ class name being added from jQuery when I try with $hrefs = $xp->query("//a/img/../@class['fancybox']");

The other option would be to sort by anchors with an href that has a filename that ends in .jpg, .gif, png. I’d be happy with that.

function content_image_check( $content ) {


$dom = new DOMDocument();
$dom->loadHTML($content);

$xp = new DOMXPath( $dom );
$hrefs = $xp->query("//a/img/../@href");


$count = $hrefs->length;
print_r( $count);

return $content;
}

if ( $count ) {
    wp_enqueue_script( 'fancybox' ); // js
    wp_enqueue_style( 'fancybox' ); // css
}

add_filter('the_content', 'content_image_check'); 

I’ve obviously registered the css and js elsewhere and only enqueue it when needed.

1 Answer
1

This method has worked in the past for checking if a shortcode exists on a page. You will have to test it and see if it fires in time to enqueue the javascript>

add_filter('the_posts', 'c3_image_check'); 
function c3_image_check($posts){
    if (empty($posts)) return $posts;
    $img_found = false; 
    foreach ($posts as $post) {
        if (stripos($post->post_content, '<img src="https://wordpress.stackexchange.com/questions/53585/)) {
            $img_found = true; // bingo!
            break;
        }
    }
    if ($img_found) {
        wp_enqueue_script("jquery.fancybox', LIB .'/jquery.fancybox.min.js', array( 'jquery' ) );
    }

    return $posts;
}

Leave a Comment