Manipulate images from WordPress post’s content with Regular Expressions

— A couple of months ago I got requested to deliver a website that would let the client publish online brochures. These brochures featured image slideshows with a description text, tags, categories etc. Many of us use WordPress not only as a blog platform but also as a multifaceted CMS. There are many features WordPress give that go beyond the blog format and that with the right adjustments and/or plugins, can be used to provide a complete solid solution. Thats why we choose to build this up on WordPress.

At first I look around to see the wp plugins available but found that none of them suited the needs of this project. I wanted to keep this very simple and easy for the client, so the best solution I came up was to let client dump any image he wanted in the post’s content-box and deal with it later with regular expressions. This way I could manage the content and present it in a good looking slideshow I could style myself.

It didn’t took much time to do it once I figured out what I wanted it to do as it’s simple PHP code:


// Start the Loop
<?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>

<?php
// Set the post content to a variable
$szPostContent = $post->post_content;

// Define the pattern to search
$szSearchPattern = '~<img [^\>]*\ />~';

// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );

// Count the results
 $iNumberOfPics = count($aPics[0]);

// Check to see if we have at least 1 image
if ( $iNumberOfPics > 0 )
{

     // Now here you would do whatever you need to do with the images
     // For this example I'm just going to echo them
     for ( $i=0; $i < $iNumberOfPics ; $i++ )
     {
          echo $aPics[0][$i];
     };

};

// ...finish the loop, etc

The code above should be fairly easy to understand. Once you printed the images its very much possible that you will like to print the text content too, the problem is that if you use the_content(); function images will be printed again as well. To solve this I had to make a little workaround to remove the images and print only the rest of the content:


// This time we replace/remove the images from the content
$szDescription = preg_replace( $szSearchPattern, '' , $szPostContent);

// Apply filters for correct content display
$szDescription = apply_filters('the_content', $szDescription);

// Echo the Content
echo $szDescription;

That’s it, quite simple solution that is indeed very powerful, I would encourage you to use WP-SuperCache or something like that to keep the server’s load low. I hope you enjoyed it, Cheers!

Tags: , , ,

Tuesday, October 7th, 2008 WordPress

→ If you find this post useful please consider inviting me a cup of tea :) Thanks!

Pass4sure offers guaranteed success in cisa as well as cisco certification plus get free demo questions for check point certifications.

30 Responses to “Manipulate images from WordPress post’s content with Regular Expressions”

  1. This is great.Thanks!!

  2. Sarah on January 30, 2009.
  3. Wow! This is a great work around over using custom fields.

    I was wondering, how do you control class output? Also is there a way to use it with conjunction to phpthumb?

  4. John on February 11, 2009.
  5. Hi John, glad you like it. You can easily control the class output and incorporate phpthumb, to do this you have to edit the loop that prints the found images:
    in the part that says echo $aPics[0][$i]; replace for something like this:

    echo '<img src="' . $aPics[0][$i] . '" class="yourclass"/>';

    And then add to the src=”" the path required to use phptumb. Hope that guides you on the correct direction.

  6. Matt on February 11, 2009.
  7. You’re a life save Matt! Thanks for the quick reply.

  8. John on February 11, 2009.
  9. Hi Matt,

    I want to retrieve only the image src path. Not whole image tag.

    Please help me to get the src path of all the images.
    Thanks
    Neel

  10. Neel on May 23, 2009.
  11. Hi Neel,

    Try using: $szSearchPattern = '~src="[^"]*"~';
    this should retrieve only the src attribute instead of the whole img element.
    cheers

  12. Matt on May 23, 2009.
  13. Thanks Matt. I will use it on my Blog.

  14. Neel on May 27, 2009.
  15. Hi, that’s really useful. I try it on a new website and it works perfectly. But I’ve got a problem, I didn’t know regex before and I don’t find something similar to your ‘~]*\ />~’. I have to find but also .
    So I put this code for
    - $szSearchPattern = ‘~]*\ />~’;
    But I only have the and not the .
    How can I do this?
    Thanks for the tutorial.

  16. Fred on July 8, 2009.
  17. exactly what i need.. thankyou.

  18. marojahan on December 7, 2009.
  19. your code worked like a charm! i’m wondering if there is a way to make the images clickable so the original image can be viewed?
    the ultimate goal would be to have them work with the lightbox plugin, but being able to click them would be helpful.
    this is what i have in the echo line:

    echo

    thanks so much

  20. jose on December 8, 2009.
  21. Awesome script, thanks! I was wondering, is there a way of getting the TOTAL image count for an entire post page? I tried modifying it, but it only seems to work in the loop.

  22. Theresa on December 11, 2009.
  23. Never mind. Figured it out with jquery. :)

  24. Theresa on December 15, 2009.
  25. Hi Matt, thanks for this code snippet. Very useful!

  26. Cedric on March 10, 2010.
  27. Hello that’s very nice!
    I just try to add something new to your code.
    I want in the part “the_content” to add the last image of the post.
    How can I manage to do this?
    Thanks.

  28. Jhon on March 10, 2010.

Leave a Reply

About Me

Matt Varone - Matias Varone - sksmatt
HI there,

I'm a freelance creative web developer, UI designer and hobbyist musician.

Twitter Status

Flickr Gallery

    Blue WallClutter drawerCS4 Replacement iconsCS4 Replacement icons