Skip to content

Instantly share code, notes, and snippets.

@jemoreto
Last active May 15, 2018 20:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jemoreto/9b215a54cecb709c959f3ebf9bacfee1 to your computer and use it in GitHub Desktop.
Save jemoreto/9b215a54cecb709c959f3ebf9bacfee1 to your computer and use it in GitHub Desktop.
Este plugin renomeia e limpa nomes de arquivos de mídia do WordPress durante o upload
<?php
/**
* Plugin Name: WP Boss // Sanitizar nome de arquivo no upload
* Plugin URI: https://www.wpboss.com.br/dicas-truques/renomear-limpar-nomes-arquivos-midia-fazer-upload-wordpress/
* Description: Este plugin renomeia e limpa nomes de arquivos de mídia do WordPress durante o upload.
* Version: 1.0
* Author: João Elton Moreto <john@wpboss.com.br>
* Author URI: https://www.wpboss.com.br/
* License: GPL-2.0+
*/
function wpboss_sanitizar_nome_arquivo( $filename ) {
$nome_sanitizado = remove_accents( $filename ); // Converter para ASCII
// Standard replacements
$invalido = array(
' ' => '-',
'%20' => '-',
'_' => '-',
);
$nome_sanitizado = str_replace( array_keys( $invalido ), array_values( $invalido ), $nome_sanitizado );
$nome_sanitizado = preg_replace('/[^A-Za-z0-9-\. ]/', '', $nome_sanitizado); // Remove todos os caracteres não alfanuméricos, exceto .
$nome_sanitizado = preg_replace('/\.(?=.*\.)/', '', $nome_sanitizado); // Remove todos os . exceto o último
$nome_sanitizado = preg_replace('/-+/', '-', $nome_sanitizado); // Substitui qualquer - duplicado por apenas um
$nome_sanitizado = str_replace('-.', '.', $nome_sanitizado); // Remove o último - se estiver no fim
$nome_sanitizado = strtolower( $nome_sanitizado ); // Caixa baixa
return $nome_sanitizado;
}
add_filter( 'sanitize_file_name', 'wpboss_sanitizar_nome_arquivo', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment