wordpress前端图片怎么上传

 4746

这篇教程给大家介绍wordpress前端图片怎么上传。

wordpress前端图片上传

最近研究个项目需要在wordpress前端上传用户头像,在网上查了些资料!解决了这个问题!

1、首先就是在需要的地方添加文件上传框了

  1. <form action="" method="post" enctype="multipart/form-data">
  2.     <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
  3.     <input type="submit" name="submit" value="Upload!" />
  4. </form>

2、对图片进行处理

  1. $post=get_post(13);//测试用
  2.  
  3. if ( $_FILES ) {
  4.  
  5.     $files = $_FILES['files'];
  6.     $count= count($files['name']);
  7.  
  8.     foreach ($files['name'] as $key => $value) {
  9.         if ($files['name'][$key]) {
  10.             $file = array(
  11.                 'name'     => $files['name'][$key],
  12.                 'type'     => $files['type'][$key],
  13.                 'tmp_name' => $files['tmp_name'][$key],
  14.                 'error'    => $files['error'][$key],
  15.                 'size'     => $files['size'][$key]
  16.             );
  17.  
  18.             $_FILES = array("files" => $file);
  19.  
  20.             foreach ($_FILES as $file => $array) {
  21.  
  22.                 $newupload = insert_attachment($file,$post->ID);//此方法将文章附加到ID为13的文章中。如果不想插入到文章可以为空""
  23.             }
  24.         }
  25.     }
  26. }

3、在functions.php文件添加功能函数

insert_attachment 该函数的第二个参数如果为空将不附加到文章中图片。

  1. function insert_attachment($file_handler,$post_id,$setthumb='false') {
  2.     global $wpdb;
  3.     // check to make sure its a successful upload
  4.     if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
  5.  
  6.     require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  7.     require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  8.     require_once(ABSPATH . "wp-admin" . '/includes/media.php');
  9.  
  10.     $attach_id = media_handle_upload( $file_handler, $post_id );
  11.  
  12.     $image_url = wp_get_attachment_image_src(  $attach_id,'full' ); 
  13.     if ($setthumb){ 
  14.         $wpdb->insert(
  15.             $wpdb->prefix . 'postmeta', array(
  16.                 'post_id' => $post_id,
  17.                 'meta_key' => 'wpcf-vi-img',
  18.                 'meta_value' => $image_url[0] 
  19.             )
  20.         );
  21.     }
  22.     return $attach_id;
  23. }

4、引用方法

  1. $image_url = wp_get_attachment_image_src(  $attach_id,'full' );//由于页面刷新的问题直接在页面使用这个方法是不生效的!需要在函数中构造此方法的功能。
  2.  
  3. //循环文章中的特征图片的方法,如果将图片附加到文章中使用这个方法可以批量输出!
  4. $imagess=get_post_meta(13,'wpcf-vi-img',false);
  5. foreach($imagess as $images){
  6.     echo  $images;
  7. }


本文网址:https://www.zztuku.com/index.php/detail-8984.html
站长图库 - wordpress前端图片怎么上传
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐