Casos de Uso
A função funciona para
- Adicionando arquivos
- Atualizando arquivos (sim, também para arquivos que já estão presentes)
- Vários arquivos
Casos sem uso
Ele aborta para trabalhos de salvamento automático, executados pelo wordpress automaticamente ou se os tipos de arquivos de destino ou tipos mime não forem atendidos.
Guloseimas
Você pode definir o nome do arquivo, os tipos de arquivo & tipos mime que você deseja alterar dentro do
função antes do loop foreach
. O arquivo obtém o ID do post e, em seguida, o ID do anexo anexado, para que você possa carregar e alterar com segurança vários arquivos por vez. Isso também se preocupa em solicitar os arquivos por (primeiro) ID de postagem e (segundo) ID de anexo.
function wpse30313_update_attachment_names($post_ID)
{
// Abort if WP does an autosave
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
# >>>> SET
// New file name:
$new_file_name = "___";
// Best would be to take the post name as file name instead of a custom title:
# $post_data = get_post( $post_ID );
# $new_file_name = $post_data->post_name;
// The file types we want be changed:
$allowed_types = array(
'image'
);
// The mime types we want to be changed:
$allowed_ext = array(
'jpg'
,'jpeg'
,'gif'
,'png'
);
# <<<< SET
// Appended by post ID for collision safety
$new_file_name = "{$new_file_name}-{$post_ID}";
// get all attached files
$attachments = get_children( array(
'post_type' => 'attachment'
,'post_parent' => $post_ID
) );
// Bulk updating attached file names
foreach ( $attachments as $att )
{
$att_ID = $att->ID;
// Append attachment ID (collision safety)
// Also allows sorting files by post & then attchment ID
$new_name = "{$new_file_name}-{$att_ID}";
$mime_type = explode( "/", get_post_mime_type( $att->ID ) );
$file_type = $mime_type[0];
$mime_type = $mime_type[1];
// Skip file types we don't want to change
if ( ! in_array( $file_type, $allowed_types ) )
continue;
// Skip mime types we don't want to change
if ( ! in_array( $mime_type, $allowed_ext ) )
continue;
// Get current file info
$file_path = get_attached_file( $att->ID );
$path = pathinfo( $file_path );
$dir = trailingslashit( $path['dirname'] );
$ext = $path['extension'];
// Build final name
$final = "{$dir}{$new_name}.{$ext}";
// Skip if the path was already changed on upload
// If we don't set this, the function wouldn't work for older files
if ( $file_path == $final )
continue;
// Update attachment-post meta info for file
rename( $file_path, $final );
update_attached_file( $att_ID, $final );
}
return;
}
add_action( 'add_attachment', 'wpse30313_update_attachment_names' );
add_action( 'edit_attachment', 'wpse30313_update_attachment_names' );
A função deve ser adicionada ao seu arquivo functions.php ou (melhor) como um pequeno plugin separado. Basta adicionar um comentário no plug-in, enviá-lo para a pasta de plug-ins e ativar.