Convert IPTC keywords to blog post tags

WordPres has a function that extract IPTC info from images, that function is wp_read_image_metadata. That function is only available on admin side and, according with the codex, it doesn’t extract IPTC keywords. But you can use iptcparse from PHP at your own to extract IPTC keywords and set them as post tags.

In your question, you said that you have already automated the proccess to attach the image as featured image of the post, so you can easily grab the image ID and the post ID during that proccess. Once you have attached the image to the post, store the post ID in $post_ID and the image ID in $image_ID and then you could do something like this:

$image = getimagesize( get_attached_file( $image_ID ), $info );

if( isset( $info['APP13'] ) ) {

   $iptc = iptcparse( $info['APP13'] );

   // 2#025 is the key in the iptc array for keywords
   if( isset( $iptc['2#025'] ) && is_array( $iptc['2#025'] ) ) {

        // Last param is true to append these tags to existing tags,
        // set it to false to replace existing tags
        // See https://codex.wordpress.org/Function_Reference/wp_set_post_tags
        wp_set_post_tags( $post_ID, $iptc['2#025'], true );

   }

}

If you set the featured image using set_post_thumbnail function (using the edit post screen to set the featured image use that function as well), you could hook the above code to updated_post_meta action (set_post_thumbnail use metadata to set the featured image):

add_action( 'updated_post_meta', function( $meta_id, $object_id, $meta_key, $_meta_value ) {

    // Check that meta 
    if( $meta_key == '_thumbnail_id' ) {

        $image = getimagesize( get_attached_file( $_meta_value ), $info );

        if( isset( $info['APP13'] ) ) {

            $iptc = iptcparse( $info['APP13'] );

            if( isset( $iptc['2#025'] ) && is_array( $iptc['2#025'] ) ) {

                wp_set_post_tags( $object_id, $iptc['2#025'], true );

            }

        }


    }

}, 10, 4 );

Note: code not tested. Just written here. You may need to handle also when the featured image is removed or changed.

Note2: I’ve re-read your question and notice that you are (quoting you) “newbie regarding to wp or coding or anything like that”. Not sure if you will understand the code above and I think the second block of code can be more helpful to you than the first.

Leave a Comment