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!























[...] Learn how to manipulate with regular expressions the images coming from the post’s content in wordpress View source [...]
[...] Visit Source. [...]