用例
添加文件更新文件(是的,也适用于已经存在的文件)多个文件无使用情形wordpress自动执行的自动保存作业,或者如果未满足目标文件类型或mime类型,则会中止。
Goodies
您可以设置文件名、文件类型和;在
foreach
环该文件获取帖子ID,然后附加附件ID,这样您可以一次安全地上载和更改多个文件。这还涉及到按(第一个)post ID和(第二个)附件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\' );
该函数应添加到函数中。php文件或(更好)作为单独的小插件。只需在顶部添加插件注释,将其上载到插件文件夹并激活即可