需要获取图像的url/src



我需要在"the_content"中检索img的src,并且还需要在最后一个锚中打印它,如下面的代码所示。我几乎尝试了我所知道的一切,也从网上找到了,但运气不好。请帮助。
我删除了所有我尝试过的东西,并放入了干净的代码,这样你们就可以很容易地理解它。

<?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; ?>

添加到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; }

获取图片的src:

<a class="lb_gallery" href="<?php echo get_first_image_url ($post->ID); ?>">

您需要解析从the_content()返回的字符串以提取img标记。这里有几种在PHP中解析HTML的方法。例如,对于DOM,它将是这样的:

<?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); ?>">

最新更新