Function and usage of delete_post_thumbnail() in wordpress


Answers ( 1 )


    The delete_post_thumbnail() function in WordPress is used to remove the thumbnail (also known as the featured image) from a specified post. Here's a detailed explanation of its usage:

    Function Signature

    delete_post_thumbnail( int|WP_Post $post ): bool

    Function Details

    • Purpose: To remove the thumbnail/featured image from a post.

    • Parameters:

      • $post (int | WP_Post): This parameter is required. It can be either the ID of the post (as an integer) or a WP_Post object representing the post from which the thumbnail should be removed.
    • Return Value:

      • This function returns a boolean value (bool).
      • It returns true if the thumbnail is successfully removed.
      • It returns false if the removal fails. This can happen if the specified post does not exist or if the post does not have a thumbnail set.

    Sample Usage

    Here's an example of how delete_post_thumbnail() might be used in a WordPress theme or plugin:

    $post_id = 123; // Assume this is the ID of the post.
    // Check if the post has a thumbnail.
    if (has_post_thumbnail($post_id)) {
        // Attempt to delete the thumbnail.
        $result = delete_post_thumbnail($post_id);
        if ($result) {
            echo "Thumbnail removed successfully.";
        } else {
            echo "Failed to remove thumbnail.";
    } else {
        echo "No thumbnail to remove.";

    In this example:

    1. We first check if the post with ID 123 has a thumbnail using the has_post_thumbnail() function.
    2. If it does, we attempt to remove it using delete_post_thumbnail().
    3. We then check the result of the operation. If $result is true, it means the thumbnail was successfully removed. Otherwise, the removal failed.

    Important Considerations

    • Post Existence: Before calling delete_post_thumbnail(), ensure that the post exists to avoid unnecessary function calls or errors.
    • Permissions: Ensure that the code or the user attempting to remove the thumbnail has the appropriate permissions to modify the post.
    • Backup: If the thumbnail might need to be restored later, consider saving its information before deletion.

    This function is useful for managing post thumbnails programmatically, especially in custom themes or plugins where dynamic control over featured images is needed.

Leave an answer