2012-12-27 85 views
0

我需要在“the_content”中检索img的src,并且还需要在最后一个锚点中打印它,如下面代码中所示。我从我的知识和互联网上尝试了几乎所有的东西,但没有运气。 plz帮助。
我删除了我尝试过的所有东西,并将干净的代码放在一边,以便你们可以轻松地理解它。需要获取图像的url/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

不使用'query_posts'对加载速度非常不利。使用'WP_Query'参见这里:http://codex.wordpress.org/Class_Reference/WP_Query#Usage – janw

回答

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

'the_content'本身已经做了回声。你需要'get_the_content' – janw

+1

@janw,谢谢。我不做WordPress。 –