我知道这是一个老问题,但我不喜欢这些答案,所以这里是我的解决方案。
这将检查文件是否存在。如果是,将更新现有附件;如果没有,它将创建一个新附件。
// Get upload dir
$upload_dir = wp_upload_dir();
$upload_folder = $upload_dir[\'path\'];
// Set filename, incl path
$filename = "{$upload_folder}/myfile-{$id}.pdf";
// Check the type of file. We\'ll use this as the \'post_mime_type\'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get file title
$title = preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) );
// Prepare an array of post data for the attachment.
$attachment_data = array(
\'guid\' => $upload_dir[\'url\'] . \'/\' . basename( $filename ),
\'post_mime_type\' => $filetype[\'type\'],
\'post_title\' => $title,
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
// Does the attachment already exist ?
if( post_exists( $title ) ){
$attachment = get_page_by_title( $title, OBJECT, \'attachment\');
if( !empty( $attachment ) ){
$attachment_data[\'ID\'] = $attachment->ID;
}
}
// If no parent id is set, reset to default(0)
if( empty( $parent_id ) ){
$parent_id = 0;
}
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment_data, $filename, $parent_id );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
在上面的示例中,我使用了。my$filename中的pdf,但您可以将其替换为任何文件名/文件类型。