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
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-includes/functions.php WP 5.2.2

<?php
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 );
	}
}

Related Functions

From tag: File system (create delete files folders)

No comments
    Hello, !     Log In . Register