SO网友:J.D.
我得到了其他论坛上一位大师的帮助。以下代码将字段“City”和“Location name”添加到附件编辑页面。它们的值来自IPTC元数据(Tag: 90, Key: Iptc.Application2.City / Tag: 27, Key: Iptc.Application2.LocationName)
并在上传图像时自动将其保存在数据库中(自定义字段:\'city
\' 和\'locationname
\'). 可以在同一附件编辑页面上手动修改这些值。
function wp_read_image_metadata_exif( $file ) {
if ( ! file_exists( $file ) ) {
return false;
}
list( , , $image_type ) = wp_getimagesize( $file );
if ( is_callable( \'iptcparse\' ) ) {
wp_getimagesize( $file, $info );
if ( ! empty( $info[\'APP13\'] ) ) {
if ( defined( \'WP_DEBUG\' ) && WP_DEBUG
&& ! defined( \'WP_RUN_CORE_TESTS\' )
) {
$iptc = iptcparse( $info[\'APP13\'] );
} else {
$iptc = @iptcparse( $info[\'APP13\'] );
}
if ( ! empty( $iptc[\'2#090\'][0] ) ) { // City.
$meta[\'city\'] = trim( $iptc[\'2#090\'][0] );
}
if ( ! empty( $iptc[\'2#027\'][0] ) ) { // Location Name.
$meta[\'locationname\'] = trim( $iptc[\'2#027\'][0] );
}
}
}
return apply_filters( \'wp_read_image_metadata_exif\', $meta, $file, $iptc );
}
function display_exif_fields ( $form_fields, $post ){
$city = get_post_meta( $post->ID, \'city\', true );
$locationname = get_post_meta( $post->ID, \'locationname\', true );
$form_fields[\'city\'] = array(
\'label\' => \'City\',
\'input\' => \'text\',
\'value\' => $city,
\'helps\' => \'\',
);
$form_fields[\'locationname\'] = array(
\'label\' => \'Location name\',
\'input\' => \'text\',
\'value\' => $locationname,
\'helps\' => \'\',
);
return $form_fields;
}
add_filter( \'attachment_fields_to_edit\', \'display_exif_fields\', 10, 2 );
function save_exif_fields( $post, $attachment ) {
$array = [ \'city\', \'locationname\' ];
foreach ( $array as $one ) {
if ( ! empty( $attachment[ $one ] ) ) {
update_post_meta( $post[ \'ID\' ], $one, $attachment[ $one ] );
} else {
delete_post_meta( $post[ \'ID\' ], $one );
}
}
return $post;
}
add_filter( \'attachment_fields_to_save\', \'save_exif_fields\', 10, 2 );
add_action(\'added_post_meta\', \'save_exif_fields_on_upload\', 10, 4);
function save_exif_fields_on_upload($meta_id, $post_id, $meta_key, $meta_value) {
$type = get_post_mime_type( $post_id );
$attachment_path = get_attached_file( $post_id );
$metadata = wp_read_image_metadata_exif( $attachment_path );
if($meta_key === \'_wp_attachment_metadata\') {
update_post_meta($post_id, \'city\', $metadata[\'city\']);
update_post_meta($post_id, \'locationname\', $metadata[\'locationname\']);
$attachment_meta = get_post_meta($post_id);
}
}