1

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

}

0

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

  wp_update_post($new_attachment_name);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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