Last active
November 13, 2023 01:26
-
-
Save oddjar/7b0b99191123ec450edcf2022393dd88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Big Daddy Media | |
Description: Deletes images older than one year from the media library. | |
Version: 1.0 | |
Author: Your Name | |
*/ | |
/* | |
generated by ChatGPT | |
*/ | |
// Register a custom admin screen for the plugin | |
add_action( 'admin_menu', 'big_daddy_media_admin_menu' ); | |
function big_daddy_media_admin_menu() { | |
add_menu_page( | |
'Big Daddy Media', // Page title | |
'Big Daddy Media', // Menu title | |
'manage_options', // Capability | |
'big-daddy-media', // Menu slug | |
'big_daddy_media_admin_screen', // Callback function | |
'dashicons-media-archive', // Icon | |
99 // Position | |
); | |
} | |
// Display the custom admin screen for the plugin | |
function big_daddy_media_admin_screen() { | |
echo '<h1>Big Daddy Media</h1>'; | |
echo '<p>This plugin deletes images older than one year from the media library.</p>'; | |
echo '<p><a href="?page=big-daddy-media&action=delete-old-images" class="button button-primary">Delete Old Images</a></p>'; | |
} | |
// Handle the "delete-old-images" action | |
add_action( 'admin_init', 'big_daddy_media_handle_actions' ); | |
function big_daddy_media_handle_actions() { | |
if ( ! isset( $_GET['page'] ) || 'big-daddy-media' !== $_GET['page'] ) { | |
return; | |
} | |
if ( ! isset( $_GET['action'] ) || 'delete-old-images' !== $_GET['action'] ) { | |
return; | |
} | |
// Delete old images | |
big_daddy_media_delete_old_images(); | |
} | |
// Delete old images from the media library | |
function big_daddy_media_delete_old_images() { | |
// Get all images in the media library | |
$images = get_posts( array( | |
'post_type' => 'attachment', | |
'post_mime_type' => 'image', | |
'post_status' => 'inherit', | |
'posts_per_page' => -1, | |
) ); | |
// Loop through all images and delete those older than one year | |
foreach ( $images as $image ) { | |
$image_date = new DateTime( $image->post_date ); | |
$current_date = new DateTime(); | |
$interval = $current_date->diff( $image_date ); | |
if ( $interval->y >= 1 ) { | |
// Log the URL of the deleted image | |
error_log( wp_get_attachment_url( $image->ID ) ); | |
// Delete the image | |
wp_delete_attachment( $image->ID ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment