Cambiar el nombre del archivo adjunto

9

¿Existe una función que me permita cambiar el nombre de archivo de un archivo adjunto, en función del ID de archivo adjunto que tengo?

Gracias! Dennis

    
pregunta FLX 05.10.2011 - 10:50

4 respuestas

20

Esto le permitirá cambiar el nombre de un archivo adjunto tan pronto como se cargue:

add_action('add_attachment', 'rename_attacment');
function rename_attacment($post_ID){

    $post = get_post($post_ID);
    $file = get_attached_file($post_ID);
    $path = pathinfo($file);
        //dirname   = File Path
        //basename  = Filename.Extension
        //extension = Extension
        //filename  = Filename

    $newfilename = "NEW FILE NAME HERE";
    $newfile = $path['dirname']."/".$newfilename.".".$path['extension'];

    rename($file, $newfile);    
    update_attached_file( $post_ID, $newfile );

}
    
respondido por el Ijaas 11.10.2011 - 06:35
4

Casos de uso

La función funciona para

  • Agregar archivos
  • Actualización de archivos (sí, también para archivos que ya están presentes)
  • Archivos múltiples

Casos sin uso

Se anula para los trabajos de guardado automático, realizados por wordpress de forma automática o si no se cumplen los tipos de archivos de destino o mimos.

golosinas

Puede configurar el nombre del archivo, los tipos de archivo & mime tipos que desea cambiar dentro de la Funciona antes del bucle foreach . El archivo obtiene la ID de publicación y luego la ID del archivo adjunto, para que pueda cargar y modificar varios archivos de forma segura a la vez. Esto también se preocupa por ordenar los archivos por (primera) ID de publicación y (segunda) ID de archivo adjunto.

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

La función se debe agregar a su archivo functions.php o (mejor) como un pequeño complemento separado. Simplemente agregue un comentario de complemento en la parte superior, cárguelo en la carpeta de complementos y active.

    
respondido por el kaiser 17.10.2011 - 14:16
3

Usaré rename de PHP y la ruta al archivo que da get_attached_file .

function rename_file( $post_id, $newname ) {
    $file = get_attached_file( $post_id );
    rename($file,dirname($file).$newname)
}

TENGA EN CUENTA que esto no se ha probado y que debe tomar precauciones extremas cuando trabaje con archivos. Probablemente necesite un cambio para que funcione, pero puede ser un buen punto de partida. Espero que esto ayude.

Avísame si te ayuda y cambiaré el código al código de trabajo real.

    
respondido por el Naoise Golden 10.10.2011 - 17:12
3
add_action('add_attachment', 'rename');
function rename($post_ID){

    $post = get_post($post_ID);
    $file = get_attached_file($post_ID);
    $path = pathinfo($file);
    $newfilename = "mynewfilename";
    $newfile = $path['dirname']."/".$newfilename.".".$path['extension'];

    rename($file, $newfile);    
    update_attached_file( $post_ID, $newfile );

}

Referencia enlace enlace

    
respondido por el Mohit Bumb 15.10.2011 - 11:14

Lea otras preguntas en las etiquetas