• Resolved stevecoy

    (@stevecoy)


    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
    getImage();
    } 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 –

    _Steve

Viewing 4 replies - 1 through 4 (of 4 total)
  • popper

    (@julialasarte)

    Try this:

    <?php
    $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.

    Thread Starter stevecoy

    (@stevecoy)

    Yes! Thanks, Julia, works like a charm.

    Thank you, this was very helpful 🙂

    *hug* to julia.lasarte
    You just made my day 😀

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Executing a function only if a post contains an image’ is closed to new replies.