Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Is there a function that allows me to change the filename of an attachment, based on the Attachment ID I have?

Thanks! Dennis

share|improve this question

4 Answers 4

up vote 13 down vote accepted
+25

This will allow you to rename an attachment as soon as its uploaded:

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

}
share|improve this answer
1  
very precisely explained :) –  booota Oct 11 '11 at 5:01
    
uhm, I get this rename(): http wrapper does not support renaming –  Bakaburg Sep 5 '13 at 21:51

Use Cases

The function works for

  • Adding files
  • Updating files (yes, also for files that are already present)
  • Multiple files

No-Use Cases

It aborts for autosave jobs, performed by wordpress automagically or if the targeted file types or mime types are not met.

Goodies

You can set the file name, file types & mime types that you want to change inside the function before the foreach loop. The file gets the post ID and then the attachment ID appended, so you can safely upload and change multiple files at a time. This also cares about ordering the files by (first) post ID and (second) attachment ID.

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

The function should be added to your functions.php file or (better) as a separate small plugin. Just add a plugin comment on top, upload it to the plugins folder and activate.

share|improve this answer
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 );

}

Reference http://codex.wordpress.org/Function_Reference/update_attached_file http://wordpress.org/tags/add_attachment

share|improve this answer

I'd use PHP's rename and the path to the file given by get_attached_file.

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

NOTE that this has been not tested and you should extreme precaution when working whith files. It probably needs changing for it to work but may be a good starting point. Hope this helps.

Let me know if it helps and I'll change the code to the actual working code.

share|improve this answer
    
This breaks WordPress's link to the file, since WordPress won't understand that a rename has happened. –  Annika Backstrom Oct 17 '11 at 13:04
    
I see. Thanks for the feedback –  Naoise Golden Oct 18 '11 at 13:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.