以编程方式Wordpress从前端上传视频

时间:2016-06-08 13:32:26

标签: php wordpress file custom-wordpress-pages

我正试图在wordpress页面中以编程方式从前端上传视频。

这是我的代码:

<?php
   if (isset($_POST['uploadvideo'])) {

    if ( ! function_exists( 'wp_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' ); 
     }

      $uploadedfile = $_FILES['photoContent'];
      $upload_overrides = array( 'test_form' => false );
      $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );


      if ( $movefile )
      {
      $image_url = $movefile["url"];
      $upload_dir = wp_upload_dir();
      $image_data = file_get_contents($image_url);
      $filename = basename($image_url);
      if(wp_mkdir_p($upload_dir['path']))
      $file = $upload_dir['path'] . '/' . $filename;
      else
      $file = $upload_dir['basedir'] . '/' . $filename;
      file_put_contents($file, $image_data);

      $wp_filetype = wp_check_filetype($filename, null );
      $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
      );

      $listing_post_id = 780 ; // post id
      $attach_id = wp_insert_attachment( $attachment, $file, $listing_post_id);

      $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
      wp_update_attachment_metadata( $attach_id, $attach_data );

      /*end file uploader*/

      }
   }

   ?>
<form method ="post" action="" name="uploadvideo"  enctype="multipart/form-data">
   <label for="ug_photo">Your Video Files
   <input type="file" value="" name="photoContent" id="ug_photo" class="" multiple="multiple"></label>
   <label for="ug_submit_button">
   <input type="submit" value="uploadvideo" name="uploadvideo" id="ug_submit_button" class="btn"></label>
</form>

但它不起作用。我已经硬编码了一个帖子ID 780,我稍后会改变它。

请帮忙。提前谢谢。

2 个答案:

答案 0 :(得分:0)

  1. 如果您不包含此文件,wp_generate_attachment_metadata() 将不起作用:- require_once( ABSPATH .'wp-admin/includes/image.php');

  2. 使用 wp_upload_bits( $_FILES['picture']['name'], null, @file_get_contents( $_FILES['picture']['tmp_name'] ) );上传图片以外的文件

答案 1 :(得分:-1)

请尝试将代码中的$uploadedfile = $_FILES['photoContent'];行更改为$uploadedfile = $_FILES['ug_photo'];