WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. stevecoy
    Member
    Posted 5 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
    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

  2. popper
    Member
    Posted 5 years ago #

    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.

  3. stevecoy
    Member
    Posted 5 years ago #

    Yes! Thanks, Julia, works like a charm.

  4. s0l1dsnak3123
    Member
    Posted 4 years ago #

    Thank you, this was very helpful :)

  5. blekfis
    Member
    Posted 4 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