将图片上传到管理后台的自定义数据库表

时间:2017-01-04 作者:Pamela Sillah

我有一个自定义的post类型,可以将用户详细信息从WordPress后端的表单插入到自定义表中。以下是表单的代码:

function display_add_user_metabox(){
  echo
  \'<form method="post" enctype="multipart/form-data" action="\'.htmlspecialchars($_SERVER[\'PHP_SELF\'] ).\'">\',
      \'<p><label for"firstname"  >First Name</label>\',
      \'<input type="text" name="firstname"></p>\',
      \'<p><label for"surname"  >Last Name</label>\',
      \'<input type="text"  name="surname"  > </p>\',
      \'<label for"nickname">Nickname</label>\',
      \'<input type=nick"text"  name="nickname" ></p>\',
      \'<label for"userpic">user Image</label>\',
      \'<input type="file"  name="userpic" ></p>\',
      \'<input type ="submit" name="submit" value="Add user" >\',
   \'</form>\';
}
以及插入用户的功能:

function add_user(){

   global $wpdb;
   $table_name = $wpdb->prefix . "users";
   $name       = $_POST[\'firstname\'];
   $surname    = $_POST[\'surname\'];
   $nickname   = $_POST[\'nickname\'];
   $upload     = wp_upload_bits($_FILES["userpic"]["name"], null, file_get_contents($_FILES["userpic"]["tmp_name"]));


     $wpdb->insert(
           $table_name,
           array(
             \'user_name\'       => $name,
             \'user_surname\'    => $surname,
             \'user_nickname\'   => $nickname,
             \'user_image\'      => $upload[\'url\']
           ),
           array(
             \'%s\',
             \'%s\',
             \'%s\',
             \'%s\'
           )
         );

}
if( isset($_POST[\'submit\']) ) {
   add_user();
}
这不会在表中插入任何内容。然而,如果我对$上传或任何与图像相关的内容发表评论,一切都很好。我错过了什么?

1 个回复
最合适的回答,由SO网友:dilip shrestha 整理而成

在global$wpdb之前包括以下内容:;

 require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
 require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
 require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');

相关推荐