_copy_image_file()
云策文档标注
概述
_copy_image_file() 是一个 WordPress 内部函数,用于复制指定的附件图像文件。它接受附件 ID 作为参数,返回新文件路径或失败时返回 false。
关键要点
- 函数参数:$attachment_id(整数,必需),表示要复制的附件 ID。
- 返回值:成功时返回新文件路径(字符串),失败时返回 false。
- 核心功能:通过 get_attached_file() 获取原始文件路径,必要时使用 _load_image_to_edit_path() 加载文件,生成唯一文件名并复制文件。
- 依赖函数:包括 wp_unique_filename()、wp_mkdir_p()、get_attached_file()、wp_basename() 等,用于文件名处理和目录创建。
- 引入版本:WordPress 3.4.0。
代码示例
function _copy_image_file( $attachment_id ) {
$dst_file = get_attached_file( $attachment_id );
$src_file = $dst_file;
if ( ! file_exists( $src_file ) ) {
$src_file = _load_image_to_edit_path( $attachment_id );
}
if ( $src_file ) {
$dst_file = str_replace( wp_basename( $dst_file ), 'copy-' . wp_basename( $dst_file ), $dst_file );
$dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) );
/*
* The directory containing the original file may no longer
* exist when using a replication plugin.
*/
wp_mkdir_p( dirname( $dst_file ) );
if ( ! copy( $src_file, $dst_file ) ) {
$dst_file = false;
}
} else {
$dst_file = false;
}
return $dst_file;
}注意事项
在使用复制插件时,原始文件所在目录可能不存在,函数通过 wp_mkdir_p() 确保目录创建。
原文内容
Copies an existing image file.
Parameters
$attachment_idintrequired-
Attachment ID.
Source
function _copy_image_file( $attachment_id ) {
$dst_file = get_attached_file( $attachment_id );
$src_file = $dst_file;
if ( ! file_exists( $src_file ) ) {
$src_file = _load_image_to_edit_path( $attachment_id );
}
if ( $src_file ) {
$dst_file = str_replace( wp_basename( $dst_file ), 'copy-' . wp_basename( $dst_file ), $dst_file );
$dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) );
/*
* The directory containing the original file may no longer
* exist when using a replication plugin.
*/
wp_mkdir_p( dirname( $dst_file ) );
if ( ! copy( $src_file, $dst_file ) ) {
$dst_file = false;
}
} else {
$dst_file = false;
}
return $dst_file;
}
Changelog
| Version | Description |
|---|---|
| 3.4.0 | Introduced. |