我想将文件上传到我的 wordpress 主题中名为 uploads 的文件夹。但它没有上传文件。任何人都可以帮忙,下面是我的代码
HTML代码
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)
[上传]
下面是functions.php文件中简码的php代码
functions upload ()
{
$file = $_FILES['file'];
$name = $file['name'];
$path = "/uploads/" . basename($name);
if (move_uploaded_file($file['tmp_name'], $path)) {
echo " Move succeed";
} else {
echo " Move failed. Possible duplicate?";
}
}
add_shortcode('upload','upload');
Run Code Online (Sandbox Code Playgroud)
谢谢
尝试使用此功能。在您的中定义它function.php
<?php
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;
}
?>
Run Code Online (Sandbox Code Playgroud)
并像这样使用
<?php
if(isset($_POST['upload']))
{
if( ! empty( $_FILES ) )
{
$file=$_FILES['file'];
$attachment_id = upload_user_file( $file );
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="upload">
</form>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10236 次 |
| 最近记录: |