[英]Unable to upload image in wordpress admin page
我正在尝试添加一个表单以在wordpress的用户个人资料管理页面中上传图像,我之前曾尝试过此代码,并且在正常的php页面中运行良好,但是当我在此wordpress函数中尝试过时它却无法正常工作。
有人可以帮忙吗?
function image_up_gall(){
?>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
add_action('edit_user_profile', 'image_up_gall');
add_action('show_user_profile', 'image_up_gall');
你可以试试这个波纹管
if (isset($_FILES["file"]["name"])) {
$destination = $_POST["dir"];
$name = $_FILES["file"]["name"];
$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
//echo $name;
//echo $tmp_name;
//echo $error;
move_uploaded_file($_FILES['file']['tmp_name'], $destination.$name);
}
首先, edit_user_profile
和show_user_profile
操作挂钩不必保存图像,您只需在其中添加一个字段即可。 所以
function image_up_gall(){
?>
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
<?php
}
add_action('edit_user_profile', 'image_up_gall');
add_action('show_user_profile', 'image_up_gall');
这是因为WordPress已经拥有自己的表单标签,只需确保它具有enctype="multipart/form-data"
第二步,使用personal_options_update
和edit_user_profile_update
您可以保存表单/上传imag,为此,请使用以下代码:
function save_profile_fields( $user_id ) {
$target_dir = "uploads/"; // I recommend to use wp_upload_dir() to get the correct path
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// here the image is uploaded and we can save it to user profile with:
update_usermeta( $user_id, 'profile_pic', $target_file );
}
}
add_action( 'personal_options_update', 'save_profile_fields' );
add_action( 'edit_user_profile_update', 'save_profile_fields' );
但我建议您使用WordPress默认媒体库来执行此操作,因为有很多代码,所以我最好为您提供指向该教程的链接: https : //rudrastyh.com/wordpress/customizable-media-uploader.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.