WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

So I used this function that allows me to change the literal filename in the directory on upload. But, it doesn't actually change the filename, hence changing the slug to the ID when attaching to a post.

For example, I upload a file with the filename "Grumpy-Cat-Ate-Nemo", it'll change to ID "89" because of the function. But it doesn't actually change the filename in the WordPress database, so it stay's as "Grumpy-Cat-Ate-Nemo.png" on WordPress even when the file is renamed to the ID.

I want the attachment url of a post to be http://example.com/grumpy-cat/89, not http://example.com/grumpy-cat/Grumpy-Cat-Ate-Nemo

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 = $post_ID;
    $newfile = $path['dirname']."/".$newfilename.".".$path['extension'];

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


share|improve this question

The add_attachment action is called after the attachment has been named. If you only want to change the name of the attachment (and the slug), you don't need to change the name of the file and can just replace the code inside rename_attachment with a call to wp_update_post.

add_action('add_attachment', 'rename_attacment');
function rename_attacment($post_ID){
  $new_attachment_name = array(
    'ID' => $post_ID, 
    'post_title' => $post_ID, // changes what you see 
    'post_name' => $post_ID // changes the slug to 89

share|improve this answer

Your Answer


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.