I have created the follow code in functions.php to add custom fields to attachments media library. Data saves as well, but I can't get data to display into the template file. Any suggestion??
Thanks!
/**
* Add custom field to media
*/
function mytheme_attachment_fields( $fields, $post ) {
$meta = get_post_meta($post->ID, 'title_en', true);
$fields['title_en'] = array(
'label' => 'Título (EN)',
'input' => 'text',
'value' => $meta,
'show_in_edit' => true,
);
$meta_two = get_post_meta($post->ID, 'description_en', true);
$fields['description_en'] = array(
'label' => 'Descripción (EN)',
'input' => 'textarea',
'value' => $meta_two,
'show_in_edit' => true,
);
$meta_three = get_post_meta($post->ID, 'title_es', true);
$fields['title_es'] = array(
'label' => 'Título (ES)',
'input' => 'text',
'value' => $meta_three,
'show_in_edit' => true,
);
$meta_four = get_post_meta($post->ID, 'description_es', true);
$fields['description_es'] = array(
'label' => 'Descripción (ES)',
'input' => 'textarea',
'value' => $meta_four,
'show_in_edit' => true,
);
return $fields;
}
add_filter( 'attachment_fields_to_edit', 'mytheme_attachment_fields', 10, 2 );
/**
* Update custom field on save
*/
function mytheme_update_attachment_meta($attachment){
global $post;
update_post_meta($post->ID, 'title_en', $attachment['attachments'][$post->ID]['title_en']);
update_post_meta($post->ID, 'description_en', $attachment['attachments'][$post->ID]['description_en']);
update_post_meta($post->ID, 'title_es', $attachment['attachments'][$post->ID]['title_es']);
update_post_meta($post->ID, 'description_es', $attachment['attachments'][$post->ID]['description_es']);
return $attachment;
}
add_filter( 'edit_attachment', 'mytheme_update_attachment_meta', 4);
/**
* Update custom field via ajax
*/
function mytheme_media_xtra_fields() {
$post_id = $_POST['id'];
$meta = $_POST['attachments'][$post_id ]['title_en'];
update_post_meta($post_id , 'title_en', $meta);
$meta_two = $_POST['attachments'][$post_id ]['description_en'];
update_post_meta($post_id , 'description_en', $meta_two);
$meta_three = $_POST['attachments'][$post_id ]['title_es'];
update_post_meta($post_id , 'title_es', $meta_three);
$meta_four = $_POST['attachments'][$post_id ]['description_es'];
update_post_meta($post_id , 'description_es', $meta_four);
clean_post_cache($post_id);
}
add_action('wp_ajax_save-attachment-compat', 'mytheme_media_xtra_fields', 0, 1);
mytheme_update_attachment_meta()
is not correct. (this is the code that fires when using the non ajax Edit Media screen.edit_attachment
is an action, not a filter, and it takes one parameter,$post_id
. I've posted a modified version of the code above in this answer which addresses these concerns: wordpress.stackexchange.com/questions/256463/…