wp_delete_attachment

Home » Functions » wp_delete_attachment

Function Name: wp_delete_attachment

In WordPress, the wp_delete_attachment function is a powerful tool that allows you to delete an attachment from the media library. It provides a convenient way to remove any unwanted files, such as images or documents, that are associated with a specific post or page.

This function takes in the attachment ID as a parameter, which is a unique identifier assigned to each attachment in WordPress. Once the function is called, it will delete the attachment file from the server and remove all associated metadata and database entries.

Usage Example: Let’s say you have a post with an attachment, and you want to delete that attachment programmatically. You can use the wp_delete_attachment function like this:

$attachment_id = 123; // Replace 123 with the actual ID of the attachment you want to delete
$result = wp_delete_attachment($attachment_id);

if ($result) {
   echo "Attachment deleted successfully!";
} else {
   echo "Failed to delete attachment.";
}

In this example, we define the attachment ID as 123 (replace it with the actual ID you want to delete) and use the wp_delete_attachment function to delete it. The function returns either true or false, indicating whether the deletion was successful or not. Based on the result, we can display an appropriate message to the user.

Remember to handle errors and validate user permissions before executing this function, as it permanently deletes the attachment and cannot be undone.

Overall, wp_delete_attachment is a handy function that simplifies the process of removing attachments from the media library in WordPress, providing developers with greater control over managing their site’s content.

Learn More on WordPress.org

WordPress snippets using the wp_delete_attachment function

Register an account to save your snippets or go Pro to get more features.