Skip to content

Instantly share code, notes, and snippets.

@XerShade
Created November 26, 2023 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XerShade/37cb73ecad6b294571739c2c513424e2 to your computer and use it in GitHub Desktop.
Save XerShade/37cb73ecad6b294571739c2c513424e2 to your computer and use it in GitHub Desktop.
WordPress: Sync Media Dates Plugin
<?php
/*
Plugin Name: Sync Media Dates
Description: Adds a button under the Media Library tab to sync the post date and post date GMT of media files to be the date the file was last modified.
Version: 1.0
Author: XerShade
*/
function sync_media_dates_page() {
add_media_page(
'Sync Media Dates',
'Sync Media Dates',
'manage_options',
'sync-media-dates',
'sync_media_dates_callback'
);
}
add_action('admin_menu', 'sync_media_dates_page');
function sync_media_dates_callback() {
if (isset($_POST['sync_media_dates_nonce']) && wp_verify_nonce($_POST['sync_media_dates_nonce'], 'sync_media_dates_action')) {
// Run the code to sync media dates.
sync_media_dates();
echo '<div class="updated"><p>Media dates synced successfully!</p></div>';
}
?>
<div class="wrap">
<h1>Sync Media Dates</h1>
<form method="post">
<?php wp_nonce_field('sync_media_dates_action', 'sync_media_dates_nonce'); ?>
<p>This will sync the post date and post date GMT of all media files to be the date the file was last modified.</p>
<p><button type="submit" class="button button-primary">Sync Media Dates</button></p>
</form>
</div>
<?php
}
function sync_media_dates() {
$media_query = new WP_Query(
array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
)
);
if ($media_query->have_posts()) {
while ($media_query->have_posts()) {
$media_query->the_post();
$attachment_id = get_the_ID();
$file_path = get_attached_file($attachment_id);
$file_created = filectime($file_path);
$file_modified = filemtime($file_path);
// Sync both post_date and post_date_gmt to the file creation date.
wp_update_post(
array(
'ID' => $attachment_id,
'post_date' => date('Y-m-d H:i:s', $file_modified),
'post_date_gmt' => get_gmt_from_date(date('Y-m-d H:i:s', $file_modified)),
'post_modified' => date('Y-m-d H:i:s', $file_modified),
'post_modified_gmt' => get_gmt_from_date(date('Y-m-d H:i:s', $file_modified)),
)
);
}
wp_reset_postdata();
}
}
@XerShade
Copy link
Author

This is just a simple plugin I made because when uploading my screenshots library from Final Fantasy XIV WordPress was setting the post date as the date uploaded not the date when the image was take (last modified), which was causing problems with trying to filter images for my gallery. This is provided as is, I may or may not update it as needed in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment