从简单的php文件脚本将excel文件上传到wordpress媒体

时间:2016-01-21 04:35:57

标签: php wordpress

我想将excel文件从外部的php文件脚本上传到wordpress。我试图搜索它但没有得到。

任何人都能帮助我吗?

2 个答案:

答案 0 :(得分:1)

if ( !function_exists('media_handle_upload') ) {
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');
    }
    $url = "http://example.com/demo.xls";
    $tmp = download_url( $url );
    if( is_wp_error( $tmp ) ){
        // download failed, handle error
    }
    $post_id = 1;
    $desc = "Description";
    $file_array = array();

    // Set variables for storage
    // fix file filename for query strings
    preg_match('/[^\?]+\.(jpg|jpe|jpeg|xls|png)/i', $url, $matches);
    $file_array['name'] = basename($matches[0]);
    $file_array['tmp_name'] = $tmp;

    // If error storing temporarily, unlink
    if ( is_wp_error( $tmp ) ) {
        @unlink($file_array['tmp_name']);
        $file_array['tmp_name'] = '';
    }

    // do the validation and storage stuff
     $id = media_handle_sideload( $file_array, $post_id, $desc );

    // If error storing permanently, unlink
    if ( is_wp_error($id) ) {
        @unlink($file_array['tmp_name']);
        return $id;
    }

    $src = wp_get_attachment_url( $id );

答案 1 :(得分:0)

试试这段代码    

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;
}
         if($_FILES['upload']['name']){
     if( ! empty( $_FILES ) ) {
  foreach( $_FILES as $file ) {
    if( is_array( $file ) ) {
   $attachment_id = upload_user_file( $file ); 
    }
  }
}
     }
    }
?>
<form enctype="multipart/form-data" method="post">
    <input type="hidden" name="posted" value="posted"/>
    <input type="file" name="upload"/>
    <input type="submit" value="Save" />
</form>