我已将<form>
<input file="file">
加入 Wordpress ,我想检索此文件以使用它。 $_POST['file'];
只给我文件名。
我可以将这些文件保存到Wordpress的媒体库中。
知道我该怎么办?
谢谢!
答案 0 :(得分:1)
<?php
// Check that the nonce is valid, and the user can edit this post.
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
// The nonce was valid and the user has the capabilities, it is safe to continue.
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
// Remember, 'my_image_upload' is the name of our file input in our form above.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
} else {
// The security check failed, maybe show the user an error.
}
来源:
https://codex.wordpress.org/Function_Reference/media_handle_upload
答案 1 :(得分:0)
php文件
if(isset($_FILES)){
foreach( $_FILES as $file )
{
if( is_array( $file ) ) {
$attachment_id = upload_user_file( $file ); //Call function
//add your code to use attachment id
}
}
}
当前已激活主题的
function upload_user_file( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}