dongqiaolong9034 2015-04-04 10:04
浏览 77

使用wordpress中的表单上传文件

I want to upload files to a folder called uploads in my wordpress theme. But it is not uploading the files. Can anybody please help , below is my code

HTML Code

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>

[upload]

Below is php code of shortcode in functions.php file

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');

Thanks

  • 写回答

2条回答 默认 最新

  • dongrong1856 2015-04-04 10:14
    关注

    try to use this function .Define this in your 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;
    }
    ?>
    

    and use like this

        <?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>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?