【问题标题】:Improving FrontEnd Uploads in Wordpress改进 Wordpress 中的前端上传
【发布时间】:2014-02-28 22:10:33
【问题描述】:

我想改进在房地产网站上传图片的过程。该网站正在运行 WordPress 3.8。该主题通过非常简单的界面提供前端提交。用户选择图像(一张一张),然后点击添加。最后,当用户提交列表时,所有图像都会立即上传。这是它的外观截图:Original Option: Listing Images

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

/*!
 * 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);

我的目标是拥有一个更灵活的系统,可以同时选择所有图像并立即开始加载。这将加快流程并改善用户体验。还可以通过移动它们以任何顺序排列它们。这是我在另一个网站上找到的一个例子。见截图:New Option: Multiple Image Upload 哪种编程语言适合这种开发?关于在哪里可以找到此应用程序的代码 sn-ps 的任何建议?在此先感谢您的帮助!!

【问题讨论】:

    标签: wordpress frontend image-uploading


    【解决方案1】:

    草稿.....你需要 jquery 和 wordpress 媒体 js..只要看下面的 js 变量名,如果有错误就会出现这些......

    函数文件中的php:

        if(function_exists( 'wp_enqueue_media' )){
        wp_enqueue_media();
        }
    

    javascript...添加到页面标题..wp_enqueue_scripts 或您的模板(首先执行此操作以确保其正常工作!)您将需要名为 upload_image_button 的元素或根据需要进行更改

        // 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();
    
      });
    

    模板文件:

        <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 返回

       if ( !empty( $_POST['submission_images'] ) ) {
       // do something with the files, set featured img, add to content or save post_meta
       }
    

    或者........我遇到了一个插件,它做得更好............对不起,它在 OOP 中并在后端设计,但你可以修改对于前端!来自 WP 的多文件上传器的问题是它要求用户在没有指导的情况下点击“CTRL”+单击....前端表单上存在大量问题...您可以轻松添加更多指导...对不起,我还没有前端示例,我还没有创建:)

    “多文件上传”

    例如

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

    保存功能

        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文件

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

    });

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

    【讨论】:

    • 感谢您的指导!!!他们非常有帮助!!我发布了有关原始选项的 JQuery 的更多信息。您认为实施推荐的脚本更好吗?还是修改原来的插件以适应新的特性?再次感谢!!
    • 我在上面更新了一个替代方法,它在后端运行得非常好!
    猜你喜欢
    • 2015-11-24
    • 2017-11-29
    • 2019-08-01
    • 2021-03-02
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2014-06-07
    相关资源
    最近更新 更多