Using EXIF and IPTC Photo Location Information in WordPress

Reading IPTC Data

Fortunately for me, php includes the iptcparse function. This produces a complete mess of an output, with cryptic array keys containing the information. Again, the internet comes to the rescue in the shape of the IPTC Keywords Reference from phpgraphy. A slight addition to the function above, and we can now get to our lovely location information. Thanks Lightroom!

/**
 * Fetch Geo Data from the image EXIF & IPTC data when using the wp_get_attachment_metadata() function
 * EXIF reading credit: {@author http://www.kristarella.com/2009/04/add-image-exif-metadata-to-wordpress/}
 * IPTC reading by {@author Gareth Cooper http://garethcooper.com/?p=1148}
 * {@see http://phpgraphy.sourceforge.net/manual/latest/apas04.html} for IPTC keywords
 */
function add_geo_exif($meta,$file,$sourceImageType) {
  //Read EXIF data
  $exif = @exif_read_data( $file );
  if (!empty($exif['GPSLatitude']))
    $meta['latitude'] = $exif['GPSLatitude'] ;
  if (!empty($exif['GPSLatitudeRef']))
    $meta['latitude_ref'] = trim( $exif['GPSLatitudeRef'] );
  if (!empty($exif['GPSLongitude']))
    $meta['longitude'] = $exif['GPSLongitude'] ;
  if (!empty($exif['GPSLongitudeRef']))
    $meta['longitude_ref'] = trim( $exif['GPSLongitudeRef'] );

  //Read IPTC data
  getimagesize($file, $info);
  if(isset($info['APP13']))
  {
    $iptc = iptcparse($info['APP13']);

    //country name
    if (!empty($iptc['2#101'][0]))
      $meta['location']['country_name'] = trim($iptc['2#101'][0]);
    //country code
    if (!empty($iptc['2#100'][0]))
      $meta['location']['country_code'] = trim($iptc['2#101'][0]);
    //province or state
    if (!empty($iptc['2#095'][0]))
      $meta['location']['province'] = trim($iptc['2#095'][0]);
    //sublocation
    if (!empty($iptc['2#092'][0]))
      $meta['location']['sublocation'] = trim($iptc['2#092'][0]);
  }

  return $meta;
}
add_filter('wp_read_image_metadata', 'add_geo_exif','',3);

Feel free to copy and paste this into your own WordPress functions.php file. As usual, suggestions for improvements are welcome in the comments below.

[GARD]


COMMENTS