Add Snippet To Project
Have you ever noticed that when you delete a post in WordPress, the featured image doesn’t necessarily go with it? This can lead to a cluttered and disorganized media library. In this article, we are going to guide you through the process of how to automatically remove the featured image when deleting a post. Say goodbye to unneeded pictures and hello to a cleaner, more organized WordPress site.
function wpturbo_autodel_associated_media($post_id) {
$media = get_children(array(
'post_parent' => $post_id,
'post_type' => 'attachment'
));
if (!empty($media)) {
foreach ($media as $file) {
wp_delete_attachment($file->ID);
}
}
}
add_action('before_delete_post', 'wpturbo_autodel_associated_media');
The above code snippet is defining a function wpturbo_autodel_associated_media($post_id)
that takes an argument $post_id
, which is the unique identifier of the post. This function will be responsible for deleting the associated media (like the featured image) when the specific post is deleted.
Inside the function, we have the method get_children()
which is a WordPress function used to retrieve all attachments belonging to the post. This function returns an array of child posts for the given post ID.
$media = get_children(array(
'post_parent' => $post_id,
'post_type' => 'attachment'
));
The get_children()
function accepts an array of arguments. In the code above, the post_parent
key is set to $post_id
to specify the parent post from which we want to get the child posts (attachments). The post_type
is set to 'attachment'
to specify that we only want to get posts of type ‘attachment’.
Next, we perform a check using the empty()
PHP function to ensure that there is media associated with the post. If the $media
array is not empty (i.e., there is associated media), we enter a foreach
loop.
if (!empty($media)) {
foreach ($media as $file) {
wp_delete_attachment($file->ID);
}
}
Within this loop, the WordPress method wp_delete_attachment()
is used, which deletes the attachment and its metadata from the system. The argument $file->ID
provides the specific ID for each attachment or media file.
The final line of the code snippet hooks the wpturbo_autodel_associated_media()
function to the before_delete_post
action hook with add_action()
. This means that immediately before any post is deleted in WordPress, our function runs, deleting all media files associated with the post in the process.
add_action('before_delete_post', 'wpturbo_autodel_associated_media');
With this code in place, you don’t have to worry about unused attachment files cluttering up your server after deleting their parent posts.