The ‘uploaded’ date field for Media Library entries is read only. Is there a way to make it editable from the Attachment Details window in upload.php?
I’ve tried the following code as a plug-in. It looks like I’m half way there. This gives me the the Uploaded Date as an input field (good).
However, I can see that I am not hooking into the proper function to actually write that value back to wp_posts along with the other post fields.
SO: How do I hook my input field so that it is part of the object that updates wp_posts?
function jch_attachment_fields_to_edit( $form_fields, $post ){
$post_date = $post->post_date;
$form_fields['post_date'] = array(
'value' => $post_date ? $post_date : '',
'label' => __( 'Uploaded Date' )
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'jch_attachment_fields_to_edit', 10, 2 );
/**
* Update attachment metadata
*
* @param int $post_ID Attachment ID.
// this actually works, but only when the user clicks 'Edit more details'
*/
function jch_edit_attachment( $attachment_id ){
$post_ID = $_REQUEST['post_ID'];
if ( isset( $_REQUEST['attachments'][$attachment_id]['media_date'] ) ) {
$media_date = $_REQUEST['attachments'][$attachment_id]['media_date'];
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_date = %s WHERE ID = %s", $media_date, $post_ID));
}
}
add_action( 'edit_attachment', 'jch_edit_attachment' );
1 Answer
It doesn’t look like you called global $wpdb
at the top of your function to access the $wpdb
class. However, I’m not sure you’re actually even getting to that part in your edit_attachment
callback.
You are trying to access the 'media_date'
property of the request, but looks like you are actually setting the name of the input to 'post date'
. You’re also using $post_id
and not $attachment_id
in your function.
Here’s your code cleaned up, hopefully this works for you.
function jch_attachment_fields_to_edit( $form_fields, $post ){
$post_date = $post->post_date;
$form_fields['post_date'] = array(
'value' => $post_date ? $post_date : '',
'label' => __( 'Uploaded Date' )
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'jch_attachment_fields_to_edit', 10, 2 );
/**
* Update attachment metadata
*
* @param int $post_ID Attachment ID.
*/
function jch_edit_attachment( $attachment_id ){
if ( empty( $_REQUEST['attachments'][$attachment_id]['post_date'] ) ) {
return;
}
$date = $_REQUEST['attachments'][$attachment_id]['post_date'];
// Make sure the date is in the correct format here... Sanitize as well...
wp_update_post([
'ID' => $attachment_id,
'post_date' => $date,
'post_date_gmt' => get_gmt_from_date( $date )
]);
}
add_action( 'edit_attachment', 'jch_edit_attachment' );
You’re going to want to make sure whatever date is going into the DB is going to be in the correct format, so you’ll want some validation as well.