How to upload video file using media upload in wor

2019-02-19 12:50发布

问题:

I have a post type which is used to upload banners in wordpress. Using custom fields for name, image/video and url. The default media upload works fine to upload image/videos, but my problem is I cannot get the video base url to the custom field.

Here is my code that is not able to get the video url. It only gives me video file name.

window.send_to_editor = function(html) {

    var imgurlar = html.match(/<img[^>]+src=\"([^\"]+)\"/);
    var imgurl = imgurlar[1];

    //image
    if( imgurl.length ){
        jQuery('#wsp_media').val(imgurl);
        jQuery('#preview-wsp-media').html('<img src="'+imgurl+'" style="max-width:30px; max-height:50px"/><input type="button"  value="Remove" class="button" onclick="removeUspMedia()"/>');
    }
    //video
    else{
        var fileurl = jQuery(html);
            //above "html" carries only video name if I click on "none" button in media library

        //check if fileurl is a video ??
        var fName = jQuery(fileurl).attr('href');

        ext = fName.split('.').pop().toLowerCase();
        var validVideos = [<?php echo "'" . implode("','", explode(' ', $this->validVideos)) . "'"?>];
        if(jQuery.inArray(ext, validVideos) == -1){
            alert('invalid video file selected');
        }else{
            jQuery('#wsp_media').val(fName);
            jQuery('#preview-wsp-media').html('<img src="<?php bloginfo('url')?>/wp-includes/images/crystal/video.png" style="max-width:30px; max-height:50px"/><input type="button"  value="Remove" class="button" onclick="removeUspMedia()"/>');
        }
    }
    tb_remove();

}

回答1:

I have found the solution myself.

Add a filter in "media_send_to_editor"

add_filter('media_send_to_editor', 'media_editor', 1, 3);

Append the video url in output html

function media_editor($html, $send_id, $attachment ){
    //get the media's guid and append it to the html
    $post = get_post($send_id);
    $html .= '<media>'.$post->guid.'</media>';
    return $html;
}

Get the media url like this

window.send_to_editor = function(html) {
        .......
        .......
        var pathArray = html.match(/<media>(.*)<\/media>/);
        var mediaUrl = pathArray != null && typeof pathArray[1] != 'undefined' ? pathArray[1] : '';
        jQuery('#wsp_media').val(mediaUrl);
        .......
        .......
    }