我正在尝试编写一个函数来重命名附件文件,无论是在上传时,还是在上传后。
我写了一个很好的函数可以做到这一点,但它会导致 WP 仪表板中缺少缩略图。我怀疑这是因为 GUID 出错了,但是 WP 现在无法更改该 GUID(我认为),所以我不确定还能做什么。希望这里有人可以提供帮助。
这就是我所拥有的,基于我在网上能找到的一切。
add_action("add_attachment", "rename_attachment", 10, 1);
function rename_attachment($post_id) {
custom_attachment_rename($post_id, "My name filename here");
}
function custom_attachment_rename( $post_id, $new_filename = 'new filename' ){
// Get path info of orginal file
$og_path = get_attached_file($post_id);
$path_info = pathinfo($og_path);
// Santize filename
$safe_filename = wp_unique_filename($path_info['dirname'], $new_filename);
// Build out path to new file
$new_path = $path_info['dirname']. "/" . $safe_filename . "." .$path_info['extension'];
// Rename the file and update it's location in WP
rename($og_path, $new_path);
update_attached_file( $post_id, $new_path );
// URL to the new file
$new_url = wp_get_attachment_url($post_id);
// Update attachment data
$id = wp_update_post([
'ID' => $post_id,
'post_title' => $new_filename,
'guid' => $new_url // Doesn't seem to work
]);
// Try this to reset the GUID for the attachment. Doesn't seem to actually reset it.
// global $wpdb;
// $result = $wpdb->update($wpdb->posts, ['guid' => $new_url], ['ID' => $post_id]);
// Update all links to old "sizes" files, or create it for new upload.
$metadata = get_post_meta($post_id, '_wp_attachment_metadata', true);
if( empty($metadata) ) {
// New upload.
$data = wp_generate_attachment_metadata($post_id, $new_path);
//update_post_meta($post_id, '_wp_attachment_metadata', $data); // Tried this. Doesn't work.
wp_update_attachment_metadata($post_id, $data); // Also doesn't work
} else {
// Regenerating an existing image
// TODO loop through $metadata and update the filename and resave? Maybe just delete it and regenerate instead?
}
// TODO Update use of the old filename in post_content throughout site
}
到目前为止,这些都是我看过的有用的帖子。
- https://wordpress.stackexchange.com/questions/166943/how-to-rename-an-image-attachment-filename-using-php
- https://wordpress.stackexchange.com/questions/30313/change-attachment-filename
- https://wordpress.stackexchange.com/a/221254/4562
奇怪的是,如果我die
在这个函数结束时,它就会起作用。所以我怀疑 WP 中的其他东西正在覆盖_wp_attachment_metadata
这个附件。这就是为什么我怀疑 GUID 是问题所在。其他东西正在通过查找附件GUID
并找到一个不再存在的文件的 URL(因为我更改了文件名)并wp_generate_attachment_metadata
在错误的文件路径上运行。这是我的预感。
我没有安装任何其他插件。