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 (null).
Usage
wp_delete_file( $file );
- $file(string) (required)
- The path to the file to delete.
Examples
#1 Delete the file test.txt from the uploads directory
$upload_info = wp_get_upload_dir(); $file = $upload_info['basedir'] . '/test.txt'; wp_delete_file( $file );
#2 Prohibit deleting files with the name test.txt using the filter
Now the example above will not delete the file test.txt
.
add_filter( 'wp_delete_file', function ( $file ) { if( 'test.txt' === basename( $file ) ){ return ''; } return $file; } );
#3 Simple example of file deletion in WordPress
// path of the file which need to be deleted. $file_path = '/home/public_html/wp-content/uploads/2020/04/photo_img_1-8.png'; wp_delete_file( $file_path );
Changelog
Since 4.2.0 | Introduced. |
wp_delete_file() wp delete file code WP 6.6.2
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 ); } }