Skip to content

Instantly share code, notes, and snippets.

@petersplugins
Last active November 14, 2016 08:13
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 petersplugins/94ae9cfe1cdbe8d1c6914086326e408a to your computer and use it in GitHub Desktop.
Save petersplugins/94ae9cfe1cdbe8d1c6914086326e408a to your computer and use it in GitHub Desktop.
<?php
// This code snippet automatically deletes the thumbnail if a post is deleted
// Add a custom function that runs before a post is deleted
add_action( 'before_delete_post', 'remove_post_thumbnail', 10 );
// This function deletes the image assigned as thumbnail from the media library
function remove_post_thumbnail( $post_id ) {
// First we have to check, of there's a thumbnail assigned to the post
if( has_post_thumbnail( $post_id ) ) {
// OK, this post has a thumbnail
// Let's get the ID
$attachment_id = get_post_thumbnail_id( $post_id );
// Before we can delete it, we have to check if it used anywhere else
// First we'll check if it is used as a thumbnail by another post
if ( empty ( get_posts( array( 'post_type' => 'any', 'post_status' => 'any', 'fields' => 'ids', 'no_found_rows' => true, 'posts_per_page' => -1, 'meta_key' => '_thumbnail_id', 'meta_value' => $attachment_id, 'post__not_in' => array( $post_id ) ) ) ) ) {
// The image is not used as thumbnail except by the post we want to delete
// Now we have theck if it's used somewhere in content - this is a bit more of work...
// We need the image URLs for all sizes
$attachment_urls = array( wp_get_attachment_url( $attachment_id ) );
foreach ( get_intermediate_image_sizes() as $size ) {
$intermediate = image_get_intermediate_size( $attachment_id, $size );
if ( $intermediate ) {
$attachment_urls[] = $intermediate['url'];
}
}
// Now we can search for these URLs in content
$used = array();
foreach ( $attachment_urls as $attachment_url ) {
$used = array_merge( $used, get_posts( array( 'post_type' => 'any', 'post_status' => 'any', 'fields' => 'ids', 'no_found_rows' => true, 'posts_per_page' => -1, 's' => $attachment_url, 'post__not_in' => array( $post_id ) ) ) );
}
if ( empty( $used ) ) {
// The image is nowhere used in content
// So finally we can delte it
wp_delete_attachment( $attachment_id, true );
}
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment