Reputation: 597
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; ?>
Upvotes: 0
Views: 255
Reputation: 604
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); ?>">
Upvotes: 2
Reputation: 44201
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); ?>">
Upvotes: 2