wp_delete_file()
Delete a file. This function is a wrapper for PHP's unlink() function — it uses wp_delete_file
filter before deleting a file.
The function use the wp_delete_file filter and then runs the unlink() PHP function. The filtes accepts the path of the file to be deleted. The unlink() function triggers only if the filter returns something (return not empty value).
Used By: wp_delete_file_from_directory()
Hooks from the function
Return
null
. Nothing.
Usage
wp_delete_file( $file );
- $file(string) (required)
- The path to the file to delete.
Examples
#1 Delete text.txt from the uploads
directory
$upload_info = wp_get_upload_dir(); $file = $upload_info['basedir'] . '/test.txt'; wp_delete_file( $file );
#2 Forbid the deletion of the file with text.txt name using the filter
So the above example will not work anymore.
add_filter( 'wp_delete_file', function ( $file ) { if ( 'test.txt' === basename( $file ) ) return ''; return $file; } );
Changelog
Since 4.2.0 | Introduced. |
Code of wp_delete_file() wp delete file WP 5.9.3
function wp_delete_file( $file ) { /** * Filters the path of the file to delete. * * @since 2.1.0 * * @param string $file Path to the file to delete. */ $delete = apply_filters( 'wp_delete_file', $file ); if ( ! empty( $delete ) ) { @unlink( $delete ); } }