Remove featured image when deleting post

Code Snippets

Remove featured image when deleting post –

Questo frammento di codice elimina automaticamente l’immagine di anteprima dalla libreria multimediale di WordPress quando si elimina un articolo.

Come funziona ?

Basta copiare ed incollare il codice sottostante nel file function.php del vostro tema e l’immagine in evidenza verrà automaticamente cancellata dalla vostra libreria multimediale.
add_action( 'before_delete_post', 'wp_remove_attachment_with_post', 10 );
function wp_remove_attachment_with_post($post_id)
{
if(has_post_thumbnail( $post_id ))
{
$attachment_id = get_post_thumbnail_id( $post_id );
wp_delete_attachment($attachment_id, true);
}
}

Fonte.
Un altro metodo interessante è quello suggerito dal sito petersplugins.com che esegue la rimozione definitiva solo se l’articolo viene cancellato definitivamente dal cestino.
// 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 );
}
}
}
}

Nota importamte: eseguite prima un backup del file functions.php, per poterlo ripristinare in caso di problemi.

Utilizziamo cookies, anche di terze parti. Maggiori informazioni. Cookies Policy. Cookies Setting.