Sanitizes filenames on the fly

Home » Snippets » Sanitizes filenames on the fly
0

Created with:

Visibility: 

public

Creator: Manny

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
/**
 * Plugin Name: WP Turbo Filename Sanitizer
 * Plugin URI: https://example.com/wpturbo-filename-sanitizer
 * Description: Sanitizes filenames on the fly for all uploaded files on your WordPress website.
 * Version: 1.0.0
 * Author: WP Turbo AI
 * Author URI: https://example.com/
 * Text Domain: wpturbo-filename-sanitizer
 */

defined( 'ABSPATH' ) || exit;

/**
 * Add filters to sanitize filenames.
 */
function wpturbo_sanitize_filenames( $filename ) {
    $sanitized_filename = sanitize_file_name( $filename );
    return $sanitized_filename;
}
add_filter( 'sanitize_file_name', 'wpturbo_sanitize_filenames', 10 );

/**
 * Add filters to sanitize filenames for all uploads.
 */
function wpturbo_sanitize_all_filenames( $metadata, $id ) {
    if ( isset( $metadata['file'] ) ) {
        $metadata['file'] = wpturbo_sanitize_filenames( $metadata['file'] );
    }
    return $metadata;
}
add_filter( 'wp_generate_attachment_metadata', 'wpturbo_sanitize_all_filenames', 10, 2 );
				

This code creates a WordPress plugin that sanitizes filenames of uploaded files on the fly. It uses two filters, sanitize_file_name and wp_generate_attachment_metadata, to modify the filename of all uploaded files by using the sanitize_file_name function that WordPress provides.

The sanitize_file_name function is called within the wpturbo_sanitize_filenames function which then returns the sanitized filename. The wpturbo_sanitize_filenames function is then added as a filter to the sanitize_file_name filter hook.

The wp_generate_attachment_metadata filter is then used in the wpturbo_sanitize_all_filenames function to sanitize filenames for all uploaded files by modifying the file metadata of the attachment.

The plugin also includes a text domain wpturbo-filename-sanitizer which can be used for language translations.

This code follows WordPress coding standards and best practices, including the use of proper spacing, comments, lowercase variable names, and the wpturbo prefix for all functions.

Register an account to save your snippets or go Pro to get more features.