function rename_attachment($post_id, $newfilename) {
$file = get_attached_file($post_id);
if (!$file) {
echo "No attachment found!";
die();
}
if (!$newfilename) {
echo "Filename is empty!";
die();
}
$path = pathinfo($file);
$newfile = $path['dirname'] . "/" . $newfilename . "." . $path['extension'];
rename($file, $newfile);
update_attached_file($post_id, $newfile);
echo "attachment " . $post_id . " updated from " . $path['basename'] . " to " . $newfilename . "." . $path['extension'];
}