0

我需要在“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; ?>
4

2 回答 2

2

您将需要解析从返回的字符串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); ?>">
于 2012-12-27T14:00:08.857 回答
2

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

要检索 img 的 src :

<a class="lb_gallery" href="<?php echo get_first_image_url ($post->ID); ?>">
于 2012-12-27T16:08:13.377 回答