0

I need to retrieve the src of an img in the "the_content" and also need to print it in the last anchor as you can see in the code below. I tried almost everything from my knowledge and also from the internet but no luck. plz help.
I removed everything that I tried and put the clean code so that you guys could easily understand it.

<?php query_posts('cat=7');?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    <div class="impresna  zoom-img" id="zoom-img">
        <?php the_content();  // it contain images>
        <span class="main"><span class="emboss">MARCA - SP</span><?php the_date(); ?>

            <a class="lb_gallery" href="need to print url of image here">+ZOOM</a></span>
            <br clear="all" />
            </div>
        <?php endwhile; ?>
<?php endif; ?>
janw
  • 6,672
  • 6
  • 26
  • 45
Kashif Waheed
  • 597
  • 4
  • 9
  • 18
  • don't use `query_posts` its very bad for loading speed. Use `WP_Query` see here: http://codex.wordpress.org/Class_Reference/WP_Query#Usage – janw Dec 27 '12 at 14:18

2 Answers2

2

You will need to parse the string returned from the_content() to extract the img tag. Here are a number of ways to parse HTML in PHP. For example, with DOM it will be something like this:

<?php
$content = get_the_content();
echo $content;
$last_src = '';

$dom = new DOMDocument;
if($dom->loadHTML($content))
{
    $imgs = $dom->getElementsByTagName('img');
    if($imgs->length > 0)
    {
        $last_img = $imgs->item($imgs->length - 1);
        if($last_img)
            $last_src = $last_img->getAttribute('src');
    }
}
?>
<a class="lb_gallery" href="<?php echo htmlentities($last_src); ?>">
Community
  • 1
  • 1
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
2

Add this to function.php

function get_first_image_url ($post_ID) {
 global $wpdb;
 $default_image = "http://example.com/image_default.jpg";   //Defines a default image
 $post = get_post($post_ID);
 $first_img = '';
 ob_start();
 ob_end_clean();
 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
 $first_img = $matches [1] [0];

 if(empty($first_img))
 { 
    $first_img = $default_image;
 }
 return $first_img; }

To retrieve the src of an img :

<a class="lb_gallery" href="<?php echo get_first_image_url ($post->ID); ?>">
asteri
  • 11,402
  • 13
  • 60
  • 84
Ahmad Suhendri
  • 604
  • 6
  • 7