[resolved] Executing a function only if a post contains an image (5 posts)

  1. stevecoy
    Posted 7 years ago #

    I'm using an image resizer to show thumbnails on archive pages. The user has the option to specify an image of their choosing to use for the thumbnail, but if they don't, the resizer automatically grabs the first image in the post. However, I don't want to execute the resizer unless a post actually has an image. So I tried something like this within The Loop:

    <?php $content = get_the_content();
    preg_match  ('/<img (.+)\"/', $content, $matches);
    if ($matches !=""){
    $hasimg = true;}
    <?php if ($hasimg)
    //grab the image and resize it
    } else {
    //do something else
    } ?>

    But my attempt to crawl the content for an <img tag isn't working, because the function is still executing on posts without images (and outputting a broken image).

    Am I on the right track here or should I put down the crack rocks?

    Thanks all -


  2. popper
    Posted 7 years ago #

    Try this:

    $content = $post->post_content;
    $searchimages = '~<img [^>]* />~';
    /*Run preg_match_all to grab all the images and save the results in $pics*/
    preg_match_all( $searchimages, $content, $pics );
    // Check to see if we have at least 1 image
    $iNumberOfPics = count($pics[0]);
    if ( $iNumberOfPics > 0 ) {
         //do stuff

    It worked for me in local echoing a simple "This post has an image" text.

  3. stevecoy
    Posted 7 years ago #

    Yes! Thanks, Julia, works like a charm.

  4. s0l1dsnak3123
    Posted 7 years ago #

    Thank you, this was very helpful :)

  5. Nicklas
    Posted 7 years ago #

    *hug* to julia.lasarte
    You just made my day :D

Topic Closed

This topic has been closed to new replies.

About this Topic