Skip to content

Instantly share code, notes, and snippets.

@1naveengiri
Created March 5, 2018 15:40
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 1naveengiri/5bf959e8437c27a7a794567bae16cb89 to your computer and use it in GitHub Desktop.
Save 1naveengiri/5bf959e8437c27a7a794567bae16cb89 to your computer and use it in GitHub Desktop.
Remove Broken Media from WordPress setup using WP_CLI Command
<?php
/**
* Plugin Name: Remove Broken Media
* Plugin Author: 1naveengiri(Naveen Giri)
* Plugin URI: http://1naveengiri.wordpress.com
* Description: WordPress plugin to remove all Broken Media post
*/
/**
* Class to clear old revision data.
*/
if ( defined( 'WP_CLI' ) && WP_CLI ) {
class Remove_Media_Command extends WP_CLI_Command {
/**
* Remove all Broken Media, It will apply a check of "if media file exist in media path?"
*
*
* ## OPTIONS
*
* [<try_it>]
* : Try it with few few no of media.
*
* [--force_delete=<true>]
* : Force delete: Delete completely without bypassing in trash.
*
* [--dry-run]
* : Dry run, just a test, no actual cleaning done.
*
* ## EXAMPLES
*
* wp broken-media remove
* wp broken-media remove 10
* wp broken-media remove --force_delete=true
*/
public function remove( $args = array(), $assoc_args = array() ) {
/**
* render all media post and check if image exist or 404 for image URL
* If 404 for media URL then delete the media post.
*/
$remove_media = isset( $args[0] ) ? intval( $args[0] ) : '-1';
$args = array(
'post_type' => 'attachment',
'posts_per_page' => $remove_media
);
$media_array = get_posts( $args );
foreach ( $media_array as $key => $media ) {
$media_path = get_attached_file( $media->ID );
$force_delete = ( isset( $assoc_args['force_delete'] ) )? $assoc_args['force_delete'] : false;
if ( file_exists( $media_path ) ) {
WP_CLI::log( sprintf( 'Found Broken Media URL %s', $media->guid ) );
WP_CLI::debug( 'Removing Media completely');
wp_delete_attachment( $media->ID, $force_delete );
WP_CLI::log( 'Media Removed');
}
}
}
}
WP_CLI::add_command( 'broken-media', 'Remove_Media_Command' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment