将文件上传到wp-content / ups中不会显示在媒体库中,那些媒体ID需要在数据库中才能显示在媒体库中。
如果您的上传文件夹中已经有文件,并且想要将其添加到数据库中
但这不是正确的解决方案,而是解决该上载文件夹的权限问题。
谢谢
,
我通过使用自定义php代码解决了该问题。
$upload = wp_upload_bits($_FILES["file"]["name"],null,file_get_contents($_FILES["file"]["tmp_name"]));
$filename = $upload['file'];
$wp_filetype = wp_check_filetype($filename,null );
// print_r($filename);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],'post_title' => sanitize_file_name($filename),'post_content' => '','post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment,$filename,$post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id,$filename );
wp_update_attachment_metadata( $attach_id,$attach_data );
set_post_thumbnail( $post_id,$attach_id );
,
Can try out another piece of code here:
--------------------------
$upload_overrides = array( "test_form" => false );
$uploaded_file = wp_handle_upload ($file,$upload_overrides);
if( isset( $uploaded_file ["file"] )) {
$file_name_and_location = $uploaded_file ["file"];
$file_title_for_media_library = $title;
$attachment = array(
"post_mime_type" => $uploaded_file_type,"post_title" => addslashes( $file_title_for_media_library ),"post_content" => "","post_status" => "inherit"
);
if( ! is_null( $post )) {
if ( ! is_numeric( $post )) {
$post = $post->ID;
} // if ()
$attachment ['post_parent'] = $post;
} // if ()
$id = wp_insert_attachment( $attachment,$file_name_and_location );
require_once( ABSPATH."wp-admin/includes/image.php" );
$attach_data = wp_generate_attachment_metadata( $id,$file_name_and_location );
wp_update_attachment_metadata( $id,$attach_data );
} // if ()
本文链接:https://www.f2er.com/3162220.html