Write IPTC keywords to image tag field

Hello,
I am building a photography website with the following situation:
the user tags his or her images with keywords in Lightroom or similar application, and the keywords end up in the IPTC data.

So far I am able to echo the IPTC data for images on a page in a list using this code:

<?php function iptc($image) {
$size = getimagesize($image->url(), $info);
if(isset($info['APP13'])){
    $iptc = iptcparse($info['APP13']);

    // Get keywords
    $keywords = '';
    $keywordcount = count($iptc["2#025"]);
    for ($i=0; $i < $keywordcount; $i++) { 
        $keywords .= $iptc['2#025'][$i].', ';
    }
    $keywords = rtrim($keywords,', ');
    echo $keywords;
}
} ?>

which i call in a template like this:

	<ol>
	<?php foreach ($page->images() as $photo): ?>
		<li>
		<?php echo iptc($photo); ?>
		</li>
	<?php endforeach ?>
	</ol>

Ideally I would like to have these keywords still be editable as a tag field associated with the images in Kirby. I was thinking about writing a hook plugin that does this, (which i tested with the date created exif data):

<?php

kirby()->hook(['panel.file.upload', 'panel.file.replace'], function($image) {
  if ($image->type() == 'image') {
    
    // Get date created from image metadata
	$datecreated = $image->exif()->timestamp();

	// Update image metadata
	$image->update(array(
		'date'    => $datecreated
	));
  }
}); 

Now, however, I am not sure how to combine the iptc function with the hook.
Can someone offer me some insight?

Where did you put the hook, in a plugin or into your config?

as for now, I wrote it inside a plugin called metadata.php

then your function should be available if it is also in a plugin that is loaded before, otherwise you can require the file within your hook conditionally.

I got it working thanks to you. My plugin code is below for reference:

<?php
// Get keywords from IPTC data
function iptc_keywords($image) {
    $size = getimagesize($image->url(), $info);
    if(isset($info['APP13'])){
        $iptc = iptcparse($info['APP13']);

        // Get keywords
        $keywords = '';
        $keywordcount = count($iptc["2#025"]);
        for ($i=0; $i < $keywordcount; $i++) { 
            $keywords .= $iptc['2#025'][$i].', ';
        }
        $keywords = rtrim($keywords,', ');

        return $keywords;
    }
};

kirby()->hook(['panel.file.upload'], function($image) {
  if ($image->type() == 'image') {
    
    // Get date created from exif data
	$datecreated = $image->exif()->timestamp();
	// Get keywords via function
	$keywords = iptc_keywords($image);

	// Update image metadata
	$image->update(array(
		'date' => $datecreated,
		'tags' => $keywords
	));
  }
});
1 Like