Last active
August 30, 2023 17:20
-
-
Save altendorfme/d914d284f6ab6fc19c5448be389f95bf to your computer and use it in GitHub Desktop.
A WP Cli command to clean attachments based on specific criteria.
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: Clean Attachments | |
Description: A plugin to clean attachments based on specific criteria. | |
Version: 1.0.2 | |
Author: Renan Bernordi | |
*/ | |
if (defined('WP_CLI') && WP_CLI) { | |
function clean_attachments_command($args, $assoc_args) | |
{ | |
$force = isset($assoc_args['force']) ? $assoc_args['force'] : false; | |
if( $force == false ) { | |
WP_CLI::line('🧪 [ Dry-run enable ]'); | |
} | |
global $wpdb; | |
$attachments = $wpdb->get_results( | |
"SELECT ID, post_parent, post_name, guid | |
FROM {$wpdb->prefix}posts | |
WHERE post_type = 'attachment' | |
AND post_name LIKE '%_avatar_%'" | |
); | |
foreach ($attachments as $attachment) { | |
$wp_upload_dir = wp_upload_dir(); | |
$metadata = wp_get_attachment_metadata($attachment->ID); | |
WP_CLI::line( '⚠️ [ ' . $metadata['file'] . ' ]' ); | |
$file_path = strtok($metadata['file'], '.'); | |
if ( $force == true ) { | |
wp_delete_attachment($attachment->ID, true); | |
} | |
WP_CLI::line( '🗑️ ' . $wp_upload_dir['basedir'] . '/' . $metadata['file'] ); | |
$related_files = glob($wp_upload_dir['basedir'] . '/' . $file_path . '*'); | |
foreach ($related_files as $file_path) { | |
if (file_exists($file_path)) { | |
echo '🗑️ ' . $file_path . PHP_EOL; | |
if ( $force == true ) { | |
unlink($file_path); | |
} | |
} | |
} | |
} | |
if( $force == false ) { | |
WP_CLI::line('🧪 [ Dry-run enable ]'); | |
} | |
} | |
WP_CLI::add_command('clean_attachments', 'clean_attachments_command'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment