WordPress at a glance

wp_delete_file() WP 4.2.0

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).

Hooks from the function

null. Nothing.


wp_delete_file( $file );
$file(string) (required)
The path to the file to delete.


#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;
} );


Since 4.2.0 Introduced.

Code of wp_delete_file() WP 5.7.1

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 );

From tag: File system (create delete files folders)

More from category: File system (WP_Filesystem)

No comments
    Log In