首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >改进Wordpress中的FrontEnd上传

改进Wordpress中的FrontEnd上传
EN

Stack Overflow用户
提问于 2014-02-28 22:10:33
回答 1查看 1.5K关注 0票数 0

我想改进上传图片的过程在一个房地产网站。这个网站运行的是WordPress 3.8。主题提供前端提交与一个非常简单的界面。用户选择图像(一个接一个),然后单击添加。最后,当用户提交列表时,所有的图像都会同时上传。这是它的外观截图:原始选项:列出图片

这是我目前使用的JQuery插件,

代码语言:javascript
复制
/*!
 * jQuery imagesLoaded plugin v2.1.1
 * http://github.com/desandro/imagesloaded
 *
 * MIT License. by Paul Irish et al.
 */

/*jshint curly: true, eqeqeq: true, noempty: true, strict: true, undef: true, browser: true */
/*global jQuery: false */

;(function($, undefined) {
'use strict';

// blank image data-uri bypasses webkit log warning (thx doug jones)
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

$.fn.imagesLoaded = function( callback ) {
    var $this = this,
        deferred = $.isFunction($.Deferred) ? $.Deferred() : 0,
        hasNotify = $.isFunction(deferred.notify),
        $images = $this.find('img').add( $this.filter('img') ),
        loaded = [],
        proper = [],
        broken = [];

    // Register deferred callbacks
    if ($.isPlainObject(callback)) {
        $.each(callback, function (key, value) {
            if (key === 'callback') {
                callback = value;
            } else if (deferred) {
                deferred[key](value);
            }
        });
    }

    function doneLoading() {
        var $proper = $(proper),
            $broken = $(broken);

        if ( deferred ) {
            if ( broken.length ) {
                deferred.reject( $images, $proper, $broken );
            } else {
                deferred.resolve( $images );
            }
        }

        if ( $.isFunction( callback ) ) {
            callback.call( $this, $images, $proper, $broken );
        }
    }

    function imgLoadedHandler( event ) {
        imgLoaded( event.target, event.type === 'error' );
    }

    function imgLoaded( img, isBroken ) {
        // don't proceed if BLANK image, or image is already loaded
        if ( img.src === BLANK || $.inArray( img, loaded ) !== -1 ) {
            return;
        }

        // store element in loaded images array
        loaded.push( img );

        // keep track of broken and properly loaded images
        if ( isBroken ) {
            broken.push( img );
        } else {
            proper.push( img );
        }

        // cache image and its state for future calls
        $.data( img, 'imagesLoaded', { isBroken: isBroken, src: img.src } );

        // trigger deferred progress method if present
        if ( hasNotify ) {
            deferred.notifyWith( $(img), [ isBroken, $images, $(proper), $(broken) ] );
        }

        // call doneLoading and clean listeners if all images are loaded
        if ( $images.length === loaded.length ) {
            setTimeout( doneLoading );
            $images.unbind( '.imagesLoaded', imgLoadedHandler );
        }
    }

    // if no images, trigger immediately
    if ( !$images.length ) {
        doneLoading();
    } else {
        $images.bind( 'load.imagesLoaded error.imagesLoaded', imgLoadedHandler )
        .each( function( i, el ) {
            var src = el.src;

            // find out if this image has been already checked for status
            // if it was, and src has not changed, call imgLoaded on it
            var cached = $.data( el, 'imagesLoaded' );
            if ( cached && cached.src === src ) {
                imgLoaded( el, cached.isBroken );
                return;
            }

            // if complete is true and browser supports natural sizes, try
            // to check for image status manually
            if ( el.complete && el.naturalWidth !== undefined ) {
                imgLoaded( el, el.naturalWidth === 0 || el.naturalHeight === 0 );
                return;
            }

            // cached images don't fire load sometimes, so we reset src, but only when
            // dealing with IE, or image is complete (loaded) and failed manual check
            // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
            if ( el.readyState || el.complete ) {
                el.src = BLANK;
                el.src = src;
            }
        });
    }

    return deferred ? deferred.promise( $this ) : $this;
};

})(jQuery);

我的目标是有一个更灵活的系统,所有的图像可以同时选择,并立即开始加载。这将加快这一过程,并改善用户体验。也可以把它们按任何顺序排列,移动它们。这是我在另一个网站上发现的一个例子。见屏幕截图:新选项:多个图像上传,什么编程语言对这个开发有好处?对于在哪里可以找到这个应用程序的代码片段,有什么建议吗?提前感谢您的帮助!!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-01 01:07:15

粗糙的draft.....you需要jquery和wordpress媒体js..just,注意下面的js变量名,如果有错误,它将与这些.

php中的函数文件:

代码语言:javascript
复制
    if(function_exists( 'wp_enqueue_media' )){
    wp_enqueue_media();
    }

javascript...add到页面header..wp_enqueue_scripts或模板(首先执行此操作以确保其工作!)您将需要您的元素名为upload_image_button或进行相应的更改

代码语言:javascript
复制
    // Uploading files

var media_uploader;

jQuery('.upload_image_button').live('click', function( event ){

    var button = jQuery( this );

    // If the media uploader already exists, reopen it.

    if ( media_uploader ) {

      media_uploader.open();

      return;

    }

    // Create the media uploader.

    media_uploader = wp.media.frames.media_uploader = wp.media({

        title: button.data( 'uploader-title' ),

        // Tell the modal to show only images.

        library: {

            type: 'image',

            query: false

        },

        button: {

            text: button.data( 'uploader-button-text' ),

        },

        multiple: button.data( 'uploader-allow-multiple' )

    });



    // Create a callback when the uploader is called

    media_uploader.on( 'select', function() {

        var selection = media_uploader.state().get('selection'),

            input_name = button.data( 'input-name' ),

            bucket = $( '#' + input_name + '-thumbnails');



         selection.map( function( attachment ) {

            attachment = attachment.toJSON();

            // console.log(attachment);

            bucket.append(function() {

                return '<img src="'+attachment.sizes.thumbnail.url+'" width="'+attachment.sizes.thumbnail.width+'" height="'+attachment.sizes.thumbnail.height+'" class="submission_thumb thumbnail" /><input name="'+input_name+'[]" type="hidden" value="'+attachment.id+'" />'

            });

         });

    });



    // Open the uploader

    media_uploader.open();

  });

模板文件:

代码语言:javascript
复制
    <span class="upload_image_button alt_button" data-input-name="images" data-uploader-     title="Upload Images" data-uploader-button-text="Add to Submission" data-uploader-allow-multiple="true">Upload</span>

php返回$_POST

代码语言:javascript
复制
   if ( !empty( $_POST['submission_images'] ) ) {
   // do something with the files, set featured img, add to content or save post_meta
   }

或者.我遇到了一个插件,它做了很多better........sorry,它在OOP和后端设计,但你可以修改前端!来自WP的多文件上传器的问题是需要用户点击"CTRL“+点击前端没有guidance....massive问题的forms...this --您可以为easily...sorry添加更多的指导--我还没有前端示例,我还没有创建:)

“多文件上传”

例如:

代码语言:javascript
复制
        public function render_meta_box_content($post)
{

    // Add an nonce field so we can check for it later.
    wp_nonce_field('miu_inner_custom_box', 'miu_inner_custom_box_nonce');

    // Use get_post_meta to retrieve an existing value from the database.
    $value = get_post_meta($post->ID, '_ad_images', true);

    $metabox_content = '<div id="miu_images"></div><input type="button" onClick="addRow()" value="Add Image" class="button" />';
    echo $metabox_content;

    $images = unserialize($value);

    $script = "<script>
        itemsCount= 0;";
    if (!empty($images))
    {
        foreach ($images as $image)
        {
            $script.="addRow('{$image}');";
        }
    }
    $script .="</script>";
    echo $script;
}

保存功能

代码语言:javascript
复制
    public function save_image($post_id)
{
    /*
     * We need to verify this came from the our screen and with proper authorization,
     * because save_post can be triggered at other times.
     */

    // Check if our nonce is set.
    if (!isset($_POST['miu_inner_custom_box_nonce']))
        return $post_id;

    $nonce = $_POST['miu_inner_custom_box_nonce'];

    // Verify that the nonce is valid.
    if (!wp_verify_nonce($nonce, 'miu_inner_custom_box'))
        return $post_id;

    // If this is an autosave, our form has not been submitted,
    //     so we don't want to do anything.
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;

    // Check the user's permissions.
    if ('page' == $_POST['post_type'])
    {

        if (!current_user_can('edit_page', $post_id))
            return $post_id;
    } else
    {

        if (!current_user_can('edit_post', $post_id))
            return $post_id;
    }

    /* OK, its safe for us to save the data now. */

    // Validate user input.
    $posted_images = $_POST['miu_images'];
    $miu_images = array();
    foreach ($posted_images as $image_url)
    {
        if(!empty ($image_url))
            $miu_images[] = esc_url_raw($image_url);
    }

    // Update the miu_images meta field.
    update_post_meta($post_id, '_ad_images', serialize($miu_images));
}

js文件

代码语言:javascript
复制
    jQuery(document).ready(function(){

jQuery('.miu-remove').live( "click", function(e) {
    e.preventDefault();
    var id = jQuery(this).attr("id")
    var btn = id.split("-");
    var img_id = btn[1];
    jQuery("#row-"+img_id ).remove();
});


var formfield;
var img_id;
jQuery('.Image_button').live( "click", function(e) {
    e.preventDefault();
    var id = jQuery(this).attr("id")
    var btn = id.split("-");
    img_id = btn[1];

    jQuery('html').addClass('Image');
    formfield = jQuery('#img-'+img_id).attr('name');
    tb_show('', 'media-upload.php?type=image&TB_iframe=true');
    return false;
});

window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
    if (formfield) {
        fileurl = jQuery('img',html).attr('src');

        jQuery('#img-'+img_id).val(fileurl);

        tb_remove();

        jQuery('html').removeClass('Image');

    } else {
        window.original_send_to_editor(html);
    }
};

});

代码语言:javascript
复制
function addRow(image_url){
if(typeof(image_url)==='undefined') image_url = "";
itemsCount+=1;
var emptyRowTemplate = '<div id=row-'+itemsCount+'> <input style=\'width:70%\' id=img-   '+itemsCount+' type=\'text\' name=\'miu_images['+itemsCount+']\' value=\''+image_url+'\' />'
+'<input type=\'button\' href=\'#\' class=\'Image_button button\' id=\'Image_button-  '+itemsCount+'\' value=\'Upload\'>'
+'<input class="miu-remove button" type=\'button\' value=\'Remove\' id=\'remove-'+itemsCount+'\' /></div>';
jQuery('#miu_images').append(emptyRowTemplate);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22106803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档