1

我使用以下编写的代码将文件移动到名为“training”的文件夹中。

  <td>
   <input type="file" name="training_image" accept="image/*" id="traing-image"value="<?php echo esc_attr( get_the_author_meta( 'training_image', $user->ID ) ); ?>" class="regular-text" />
  </td>

为了保存图像,我写了这个

$training_path = time().'_'.$_FILES['training_image']['name'];
$tmp_file_name = $_FILES['training_image']['tmp_name'];
$upload_dir = wp_upload_dir();
if($training_path){
       move_uploaded_file($tmp_file_name,$upload_dir['baseurl'].'/training/'.$training_path);
}
update_user_meta( $user_id, 'training-image', $training_path );

但我无法得到任何结果。我有没有做错什么。请帮我。

这是我的全部代码

function training_user_profile_fields( $user ) { ?>
<h3><?php// _e("Extra profile information", "blank"); ?></h3>

<table class="form-table">
  <tr>
    <th><label for="traing-image"><?php _e("Upload Your Training Certificate:"); ?></label></th>
      <td>
       <input type="file" name="training_image" id="traing-image"value="<?php echo esc_attr( get_the_author_meta( 'training_image', $user->ID ) ); ?>" class="regular-text" />
      </td>
    </tr>
</table>
<?php }

add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

function save_extra_user_profile_fields( $user_id ) {

if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
$training_path = time().'_'.$_FILES['training_image']['name'];
$tmp_file_name = $_FILES['training_image']['tmp_name'];
echo "filename".$_FILES['training_image']['tmp_name']; exit;
$upload_dir = wp_upload_dir();
if($training_path){
       move_uploaded_file($tmp_file_name,$upload_dir['baseurl'].'/training/'.$training_path);
}
update_user_meta( $user_id, 'training-image', $training_path );
}
4

1 回答 1

2

你这样做是不对的。$upload_dir['baseurl']URL上传目录而不是absolute path给目录。您不能使用 URL 上传或移动文件。

HTTP wrapper does not support writeable connections

所以$upload_dir['baseurl']应该改为$upload_dir['basedir']。

它应该是

$training_path = time().'_'.$_FILES['training_image']['name'];
$tmp_file_name = $_FILES['training_image']['tmp_name'];
$upload_dir = wp_upload_dir();
if($training_path){
       move_uploaded_file($tmp_file_name,$upload_dir['basedir'].'/training/'.$training_path);
}
update_user_meta( $user_id, 'training-image', $training_path );

还要确保您的表单enctype设置为multipart/form-data (enctype="multipart/form-data")

更新

WordPress 个人资料表单默认没有enctype属性。您可以使用钩子添加它。将此添加到您的主题中functions.php

add_action('user_edit_form_tag', 'add_enctype');

function add_form_enctype () {
    echo  'enctype="multipart/form-data"';
}

希望这可以帮助

于 2013-04-09T08:51:16.807 回答