从简单的PHP文件脚本将Excel文件上传到WordPress媒体


upload excel file to wordpress media from simple php file script

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

有人可以帮助我吗?

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

试试这段代码

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>