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.