I’ve added a few custom fields to the WordPress image uploader using the hooks attachment_fields_to_edit
and attachment_fields_to_save
. Everything works very well, except when a field is erased by the user. For example, the field used to say ‘Oil Painting’ and the user erased it, wanting the field to be blank – but the field still says ‘Oil Painting’. Changing the text to something else works fine however. Any ideas why this is happening? Thanks in advance
Here is my code:
// Add custom fields to the media uploader
function wpf_fields_edit( $form_fields, $post ) {
$post->post_type == 'attachment';
$form_fields[ 'wpf_g_medium' ] = array(
'label' => __( 'Medium' ),
'input' => 'text',
'value' => get_post_meta( $post->ID, '_wpf_g_medium', true )
);
$form_fields[ 'wpf_g_medium' ][ 'label' ] = __( 'Medium' );
$form_fields[ 'wpf_g_medium' ][ 'input' ] = 'text';
$form_fields[ 'wpf_g_medium' ][ 'value' ] = get_post_meta( $post->ID, '_wpf_g_medium', true );
// A couple more fields are added here, using the same code
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'wpf_fields_edit', NULL, 2 );
// Save the fields' data
function wpf_fields_save( $post, $attachment ) {
$fields = array('wpf_g_medium', 'wpf_g_dimen', 'wpf_g_collabs');
foreach( $fields as $field ) {
$key = '_' . $field;
if( isset( $attachment[ $field ] ) ) {
if( trim( $attachment[ $field ] ) == '' ) $post[ 'errors' ][ $field ][ 'errors' ][] = __( 'Error! Something went wrong.' );
else update_post_meta( $post[ 'ID' ], $key, $attachment[ $field ] );
}
}
return $post;
}
add_filter( 'attachment_fields_to_save', 'wpf_fields_save', NULL, 2 );
// Print the values, called in attachment.php
function get_artwork_fields_info() {
global $post;
$fields = array('wpf_g_medium', 'wpf_g_dimen', 'wpf_g_collabs');
$title = $post->post_title;
if( $fields ) {
echo '<ul id="artwork-meta"><li><em>' . $title . '</em></li>';
foreach ( $fields as $field ) {
$key = '_' . $field;
$meta = get_post_meta( $post->ID, $key, true );
if ( $meta ) {
echo '<li>';
echo $meta;
echo '</li>';
}
}
echo '</ul>';
}
}
You are checking if the field is empty. Try to update it if its empty as well
Try