在wordpress帖子中获取第一张图片的其他属性

时间:2012-04-06 19:04:00

标签: php wordpress

这似乎是一个常用的功能,可以从帖子中获取第一张图片

function get_first_image() {
  global $post, $posts;
  $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)){ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}

这只返回src。我需要扩展它以在一个数组中返回该图像的标题,标题和描述。怎么办呢?

2 个答案:

答案 0 :(得分:1)

也许您会在StackExchange Wordpress网站获得更好的运气。祝你好运。

答案 1 :(得分:0)

制作能够为您检索此数据的正则表达式将非常困难。 HTML不是常规语言。如果Wordpress站点上的HTML格式发生变化,您的代码也不会非常有弹性。如果您使用实际的HTML解析器,则提取数据会更容易。有关在PHP中执行此操作的最佳工具的一些指导,请参阅How do you parse and process HTML/XML in PHP?