简体   繁体   English

在Wordpress中上传前端媒体

[英]Front End Media Uploading in Wordpress

I'm in need of some help! 我需要一些帮助! :) :)

What I'm trying to do is let a user create a post from the front end. 我想做的是让用户从前端创建帖子。 With a preview window of how the post will look like when published. 带有预览窗口,显示发布时帖子的外观。 This I have already accomplished. 我已经完成了。 Now I'm trying to allow the user to upload a image directly into the media library. 现在,我试图允许用户将图像直接上传到媒体库中。 This upload needs to happen as soon as the user has chosen the file with the follow code: 用户选择带有以下代码的文件后,就需要立即进行上传:

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

I don't want any page load, is there a way to get the file without using a submit button? 我不希望加载任何页面,有没有一种方法可以在不使用提交按钮的情况下获取文件? Also how do I handle the actual file upload, my google skills found this function: 另外,我该如何处理实际的文件上传,我的Google技能发现了此功能:

function insert_attachment($file_handler,$post_id,$setthumb='false') {

  // check to make sure its a successful upload
  if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  require_once(ABSPATH . "wp-admin" . '/includes/media.php');

  $attach_id = media_handle_upload( $file_handler, $post_id );

  if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
 return $attach_id;
}

But this function hooks the upload to a post, I just want it to go straight into the library without being connected to a post. 但是此功能将上传链接到帖子,我只希望它直接进入库而不连接到帖子。 Also I assume the $file_handler is the name of the form? 我还假设$ file_handler是表单的名称吗? I also assume that $_FILES doesn't exists unless the user has clicked a submit button. 我还假定除非用户单击了提交按钮,否则$ _FILES不存在。

I'm prolly way off here, talking out of my ass. 我很想离开这里,从屁股里出来。 So any help would be appriciated. 因此,将寻求任何帮助。 Any WP-gurus available? 有可用的WP-gurus吗? :D :D

I had the same problem. 我有同样的问题。 The Wordpress Documentation helps: http://codex.wordpress.org/Function_Reference/wp_handle_upload http://codex.wordpress.org/Function_Reference/wp_insert_attachment WordPress文档可以帮助: http : //codex.wordpress.org/Function_Reference/wp_handle_upload http://codex.wordpress.org/Function_Reference/wp_insert_attachment

UPDATE: $key is the name of the type="file" 更新:$ key是type =“ file”的名称

I just added the guid value, because it doesn't seem to be added (and maybe there are better ways, then including admin.php: 我刚刚添加了guid值,因为似乎没有添加它(也许还有更好的方法,然后包括admin.php:

        require_once(ABSPATH . 'wp-admin/includes/admin.php');
        // step one upload file to server
        $file_return = wp_handle_upload($_FILES[$key], array('test_form' => false));

        if(isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
            echo 'not working again :(';
        }
        else {
            /**
             * See http://codex.wordpress.org/Function_Reference/wp_insert_attachment
             * 
             */
            $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']
            );
            $attach_id = wp_insert_attachment( $attachment, $file_return['url'] );
            // you must first include the image.php file
            // for the function wp_generate_attachment_metadata() to work
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
            wp_update_attachment_metadata( $attach_id, $attach_data );

        }


    }

Ok, I'm getting forward. 好吧,我要前进。 I'm now using this jquery plugin for image uploading -> http://lagoscript.org/jquery/upload 我现在正在使用这个jquery插件上传图片-> http://lagoscript.org/jquery/upload

Which is very lightweight and works great. 它非常轻巧,效果很好。 Uploads the image to my computer without refreshing. 将图像上传到我的计算机,而无需刷新。 It saves the file in a temp dir on my server, what I'm planning to do now is somehow inject this image into the media library (and then delete it from the temp folder), but this seems harder than it should. 它将文件保存在服务器的temp目录中,我现在打算做的就是以某种方式将此映像注入到媒体库中(然后从temp文件夹中删除它),但这似乎比应做的要难。

Is there any way I can add a image to the media library with php-code, using only a image url? 有什么方法可以仅使用图像URL将图像添加到带有php代码的媒体库中? I can't seem to find one, but since WP has this feature in the admin-area already there must be a way. 我似乎找不到一个,但是由于WP在管理区域中具有此功能,因此已经必须有一种方法。

The easiest way seems to be just creating a custom field that stores the image for that post, but I really want to be able to use WPs thumbnail functions, not only for looping, but for resizing etc. 最简单的方法似乎只是创建一个自定义字段,用于存储该帖子的图像,但是我真的希望能够使用WP缩略图功能,不仅用于循环播放,还可以用于调整大小等。

Any pointers? 有指针吗?

I am using this code working is fine 我正在使用此代码工作正常

javascript javascript

<script src="<?php bloginfo( 'template_url' ); ?>/image_file/jquery.ui.widget.js"></script>
<script src="<?php bloginfo( 'template_url' ); ?>/image_file/jquery.iframe-transport.js"></script>
<script src="<?php bloginfo( 'template_url' ); ?>/image_file/jquery.fileupload.js"></script>
<script src="<?php bloginfo( 'template_url' ); ?>/image_file/jquery.fileupload-validate.js"></script>

<script>

$(function () {
    'use strict';

    var url =  '<?php bloginfo( 'template_url' ); ?>/upload.php';
    $('#fileupload').fileupload({


         add: function(e, data) {
                var uploadErrors = [];

                if(data.originalFiles[0]['size'] > 2000000) {
                    uploadErrors.push('Filesize is too big');
                }
                if(uploadErrors.length > 0) {

                    $("#errormessage").show();
                    $("#errormessage").html(uploadErrors.join("\n"));

                } else {
                    data.submit();
                    $("#errormessage").hide();
                }
        },


        url: url,
        dataType: 'json',

        done: function (e, data) {


             if(data._response.result.response=="errortype"){
                 $("#errormessage").show();
                $("#errormessage").html("Not an accepted file type ");
                $("#progress").hide();
             }
             else 
             {
                  $("#progress").show(); 
                  var url=data._response.result.upload_info.url;
                 if(url=='')
                    {

                    }
                   $("#file_url").val(url);


                     }



        },
        progressall: function (e, data) {

            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').html( progress + '%');
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        }
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>

HTML 的HTML

< <

span class="input__label-content input__label-content--akira" >UPLOAD A PHOTO OF YOUR RECEIPT**</span>
               <span id="fileupload"> <input type="file" name="upload_file" multiple></span>

    </span>

    <input type="hidden" name="file_url" value="" id="file_url" />

upload.php

<?php

    require("../../../wp-load.php");
    global $wpdb;
    if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfiles = $_FILES['upload_file'];

if(strtolower($uploadedfiles['type'])=='image/jpeg' || strtolower($uploadedfiles['type'])=='image/gif' || strtolower($uploadedfiles['type'])=='image/png' || strtolower($uploadedfiles['type'])=='image/pjpeg' || strtolower($uploadedfiles['type'])=='image/x-png'){
//

$upload_overrides = array( 'test_form' => false );
$results=array();


  if ($uploadedfiles['name']) {
    $file = array(
      'name'     => $uploadedfiles['name'],
      'type'     => $uploadedfiles['type'],
      'tmp_name' => $uploadedfiles['tmp_name'],
      'error'    => $uploadedfiles['error'],
      'size'     => $uploadedfiles['size']
    );


    $movefile = wp_handle_upload( $file, $upload_overrides );

  if ( $movefile ) {

       $data=array('result'=>'success','upload_info'=>$movefile);

       $filename = $movefile['upload_file']['file'];

      $filetype = wp_check_filetype( basename( $filename ), null );



      $wp_upload_dir = wp_upload_dir();


      $attachment = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
        'post_mime_type' => $filetype['type'],
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit'
      );

      $attach_id = wp_insert_attachment( $attachment, $filename, $id );


      require_once( ABSPATH . 'wp-admin/includes/image.php' );


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



  } else {
      $data=array('result'=>'error','upload_info'=>null);
  }

  $data['request']=$_FILES;

  }
}
else 
{
    $data=array('response'=>'errortype','upload_info'=>null);
}

    echo json_encode($data);


?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM