我想将文件上传到我的wordpress主题中名为uploads的文件夹中。但它不是上传文件。任何人都可以帮忙,下面是我的代码
HTML代码
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
[上传]
下面是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');
由于
答案 0 :(得分:2)
尝试使用此功能。在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;
}
?>
并像这样使用
<?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>
答案 1 :(得分:1)
如果您想在自定义文件夹中上传,可以使用此功能
在functions.php
function upload_user_file( $file = array(),$path ) {
if(!empty($file))
{
$upload_dir=$path;
$uploaded=move_uploaded_file($file['tmp_name'], $upload_dir.$file['name']);
if($uploaded)
{
echo "uploaded successfully ";
}else
{
echo "some error in upload " ;print_r($file['error']);
}
}
}
在您的template file
中制作表格
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="upload">
</form>
在get_header();
功能
if(isset($_POST['upload']))
{
if( ! empty( $_FILES ) )
{
$file=$_FILES['file']; // file array
$upload_dir=wp_upload_dir();
$path=$upload_dir['basedir'].'/myuploads/'; //upload dir.
if(!is_dir($path)) { mkdir($path); }
$attachment_id = upload_user_file( $file ,$path);
}
}