Created
June 13, 2019 14:39
-
-
Save raphaelportmann/091b0718e3a256fde780579f3c2c9e67 to your computer and use it in GitHub Desktop.
remove images from wordpress db which no longer exist
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 | |
// Only run the code if we are in the admin | |
if ( is_admin() ) : | |
class WordPressdeleteMissingImages { | |
// Action/Filter Hooks | |
function __construct() { | |
add_action( 'admin_menu', array( &$this, 'add_page' ) ); | |
add_action( 'admin_init', array( &$this, 'admin_init' ) ); | |
} | |
function admin_init() { | |
if ( array_key_exists( 'delete-missing-images', $_GET ) ) { | |
$imgs = get_posts("post_type=attachment&numberposts=-1"); | |
foreach($imgs as $img){ | |
$file = get_attached_file($img->ID); | |
if(!file_exists($file)){ | |
wp_delete_post( $img->ID, false ); | |
} | |
} | |
wp_redirect( admin_url() . '?missing-images-deleted' ); | |
exit(); | |
} | |
else if ( array_key_exists( 'missing-images-deleted', $_GET ) ) | |
add_action( 'admin_notices', array( &$this, 'ok_notice' ) ); | |
} | |
// admin_notices action hook operations | |
// Inform the user that the dirty work is done | |
function ok_notice() { | |
echo '<div id="message" class="updated fade"><p><strong>Missing Images deleted.</strong></p></div>'; | |
} | |
// admin_menu action hook operations | |
// Add the delete menu item | |
function add_page() { | |
global $submenu; | |
if ( current_user_can( 'level_10' ) && function_exists( 'add_management_page' ) ) | |
$submenu['upload.php'][667] = array( 'delete Missing Images', 'manage_options' , admin_url() . '?delete-missing-images' ); | |
} | |
} | |
$WordPressdeleteMissingImages = new WordPressdeleteMissingImages(); | |
endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment