我需要在“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; ?>
答案 0 :(得分:2)
您需要解析从the_content()
返回的字符串以提取img
标记。以下是一些ways to parse HTML in PHP。例如,对于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); ?>">
答案 1 :(得分: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); ?>">