2012-07-26 34 views
0

我经常使用这个功能来提取后的图像:WP/PHP函数来提取图像不起作用

function first_post_image($content) { 
$first_img = ''; 
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches); 
$first_img = $matches [1] [0]; 
return $first_img; 
} 

然后我展示用下面的代码

<?php $postimage = first_post_image(get_the_content()); ?> // catch the image 
<img src="<?php echo $postimage; ?>" /> //view the image 
图像

现在我尝试在我的最后一个模板(wp)中使用此功能,但图像未显示。我可以看到标签img和src属性,但它是空的。

有人可以帮助我吗?谢谢

回答

0

你做了var_dump($postimage);看看函数返回什么?

这是一个工作,而不是返回一个空数组,如果没有图像它将返回false,所以你可以指定一个备份或默认图像。

/** 
    * Extracts the first image in the post content 
    * 
    * @param object $post the post object 
    * @return bool|string false if no images or img src 
    */ 
    function extract_image($post) { 
     $html = $post->post_content; 
     if (stripos($html, '<img') !== false) { 
      $regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im'; 
      preg_match($regex, $html, $matches); 
      unset($regex); 
      unset($html); 
      if (is_array($matches) && ! empty($matches)) { 
       return $matches[2]; 

      } else { 
       return false; 
      } 
     } else { 
      return false; 
     } 
    } 
0

我做了一些测试,最后我解决了这个问题。我不知道我是否犯了一个错误,但代码是相同的,现在可以正常工作。 谢谢。