0

This seems to be a commonly used function to get the first image out of a post

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;
}

This only returns the src. I need this expanded to also return the title, caption and description of that image in one array. How can this be done??

2Yootz
  • 3,971
  • 1
  • 36
  • 31

2 Answers2

1

Perhaps you will receive better luck at the StackExchange Wordpress site. Good luck.

Community
  • 1
  • 1
csi
  • 9,018
  • 8
  • 61
  • 81
0

It would be very difficult to craft a regular expression that would be able to retrieve this data for you. HTML is not a regular language. Your code would also not be very resilient if the format of the HTML on the Wordpress site changes. It would be easier to extract the data if you used an actual HTML parser. See How do you parse and process HTML/XML in PHP? for some guidance on the best tools for doing this in PHP.

Community
  • 1
  • 1
Jacob
  • 77,566
  • 24
  • 149
  • 228
  • It didn't know if there was some way to take the url that is extracted from the regular expression (a unique permalink), and use that to reference the other data through a mysql call?? – 2Yootz Apr 07 '12 at 02:06