Wordpress 收到添加文件到媒体库中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$filename = '2019/03/test.mp4';
$uploadpath = wp_get_upload_dir();
//return $uploadpath;
$f_dir = '/'.$filename;
$file = $uploadpath['basedir'].$f_dir;
$post_parent_id = 0;
if(file_exists($file)){
if ( !function_exists('media_sideload_image') ){
//require_once( ABSPATH.'/wp-admin/includes/media.php' );
//require_once( ABSPATH.'/wp-admin/includes/file.php' );
require_once( ABSPATH.'/wp-admin/includes/image.php' );
}
$wp_filetype = wp_check_filetype(basename($file), null ); //获取 mime类型
$title = preg_replace('/\.[^.]+$/', '', basename($file));
// Construct the attachment array.
$attachment = array(
'post_mime_type' => $wp_filetype,
'guid' => $uploadpath['baseurl'].$f_dir,
'post_parent' => $post_parent_id,
'post_title' => $title,
'post_content' => '', // 指定空的内容
'post_status' => 'inherit' // 上传文件的状态固定是inherit
);
// Save the attachment metadata
$attach_id = wp_insert_attachment($attachment, $file, $post_parent_id);
if ( !is_wp_error($attach_id) ){
wp_update_attachment_metadata( $attach_id, wp_generate_attachment_metadata( $attach_id, $file ) );
}
}
`
Reference
  1. wp_insert_attachment.php
  2. WordPressの「wp_insert_attachment」を使って、特定の投稿に対して添付ファイルをメディアライブラリにアップロードする
  3. Uncaught Error: Call to undefined function wp_generate_attachment_metadata() @ wp-cron