gpt4 book ai didi

php - 使用 WordPress 中的表单上传文件

转载 作者:行者123 更新时间:2023-12-03 06:50:20 25 4
gpt4 key购买 nike

我想将文件上传到我的 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');

谢谢

最佳答案

尝试使用此函数。在您的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>

关于php - 使用 WordPress 中的表单上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29445097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com