2012-12-27 84 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。 –