Thursday, January 2, 2014

How to extract all images and image attributes from a wordpress post (without a plugin) - wordpress

Imagine displaying a  dynamic grid with multiple images (say 10).So,what would you do?Let's see.
You would create 10 different posts,insert a different image in each post and call it into a Wordpress loop.Now imagine doing that for 50 or even more...Sounds terribly tedious,right?

Well,here's a full fledged solution to this problem..So all you need is a single wordpress post and multiple images in it...You can add /edit/delete them whenever you want.And how do we achieve this??By simply manipulating "the_content".:)



So begin off by creating a WordPress post with multiple images.I would also categorize this post under a category say "med".



Now,in front-page.php,I would simply add this bit of regex code wherever I want the images to appear..In this example,my images would appear in a caraousel.


<ul id="carousel_container">
<?php query_posts('category_name=med'); if ( have_posts() ) while ( have_posts() ) : the_post();  ?>
<?php 
global $more;
$more = 1;
$link = get_permalink();
$content = get_the_content();
$count = substr_count($content, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
    $imgBeg = strpos($content, '<img', $start);
    $post = substr($content, $imgBeg);
    $imgEnd = strpos($post, '>');    
    $postOutput = substr($post, 0, $imgEnd+1);   
     $imgBeg1 = strpos($postOutput, 'alt="',0);
    $post1 = substr($postOutput, $imgBeg1);
    //echo $post1;
    $imgEnd1 = strpos($post1, 'src');
    $postOutput1 = substr($post1, 5, $imgEnd1-7);
    $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);
    if(stristr($postOutput,'<img')) { echo '<li>'.$postOutput.'<div class="carousel_caption"><h4>'.$postOutput1.'</h4></div></li>'; }    
    $start=$imgBeg+1;
 

}
?>
<?php endwhile; ?>
</ul>

So,in the above code, I have simply extracted the images from the <img> tag and their "alt" attributes so that they can show up under each image.The "alt" caption can be created while defining the images in the Wordpress post.


The final carousel would be displayed as follows:


So didn't I just save a lot of time for you?

Post a Comment