In WordPress I’m trying to enqueue a script for a jQuery gallery only for posts that got attachments.
I got this simple function that works for single posts:
function gotImages()
{
$attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') );
return ( !empty($attachments) ? true : false );
}
When I call gotImages() in functions.php it returns true for a single post with attachments but false for the home page with several posts if the first post doesn’t have attachments.
How can I modify this so it works for more than one post i.e. on the home page where I’m displaying 10 posts?
Thanks!
Finally worked out a rough working solution. It’s probably not the final version but here’s my solution for anyone who might be interested.
This function if put in functions.php will read through the content of the current loop and scan it for
<IMG>tags. If one or more tags are found it returns true otherwise false.Now I can use this to conditionally enqueue scripts or stylesheets depending on if a post got any images.
For example like this:
I’m not sure yet how ‘expensive’ this function is but the site I’m working on it quite small so for now it’s not a big deal of it adds a few ms to the process time.