0

I'm using Advanced Custom Fields and a WYSIWYG field type. Can you determine via php if that field has an image in the content OR is there a better was to evaluate this.

For example, if I upload an image into the editor and float if right of the text - I intend on treating the rendered container differently than a container without the image.

1 Answer 1

3

There isn't really a built-in way in WordPress to determine if a content field has an image in it, but you can use standard PHP functions to check. For example, I've used a similar technique to check if a post's featured image has also been inserted into the post content, and if so, haven't shown the featured image again.

You haven't included any of your code, so this is just a sample you'll need to work in to what you already have.

The strpos() function will tell you if a specific string is inside another string. For example:

if( strpos( get_the_content(), '<img ' ) ){ /* this content has an image */ }

You could perhaps use this to add classes to your content container, so you can treat it differently in the CSS:

<?php
$image_class = strpos( get_the_content(), '<img ' ) ) ? 'has-image' : 'no-image';
?>

<div class="post-content <?php echo $image_class; ?>">
3
  • 1
    FWIW I've just spent a day or two looking through wp-includes/media.php and related core files and can concur that there isn't a helpful function for this. There are functions to pull out a list of media embeds or gallery images from a piece of content, and get_media_embedded_in_content might be usable for the OP's purpose but if all you're after is a yes/no on an image being present then Tim's answer seems the easy way to check. Commented Aug 4, 2016 at 14:49
  • Tim, Thanks for the follow up on this! I ended up checking via jquery on load and just curious which would be technically more efficient? I know I originally asked about doing this in php. Just curious. @AndyMacaulay-Brook, thanks for that reference,I wasn't aware something like this existed!!
    – Javi
    Commented Aug 9, 2016 at 2:02
  • My rule of thumb is - generally - if it can be done in the PHP, do it there. It's almost always more efficient to do it server-side, especially because if what you're doing is cached, it's pretty much done once rather than many times. In this case also, you avoid a flash of unstyled content before jQuery applies the class. This is just a rule of thumb though... every situation is different :)
    – Tim Malone
    Commented Aug 9, 2016 at 4:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.