Question

I want to improve the process of uploading pictures in a Real Estate Website. This website is running WordPress 3.8. The theme offers front end submission with a very simple interface. The user selects the images (one by one) and then clicks to add. Finally when the user submit the listing all the images are uploaded at once. This is the screenshot of how it looks: Original Option: Listing Images.

This is the JQuery Plugin I am currently using,

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

My goal is to have a more flexible system, where all the images can be selected at the same time and it starts loading right away. This will speed up the process and improve user experience. Also to arrange them in any order by moving them around. This is an example I found on another website. See screenshot: New Option: Multiple Image Upload What programing language is good for this development? Any recommendations of where I can find code snippets for this application? Thanks in advance for your help!!

Était-ce utile?

La solution

rough draft.....you need jquery and wordpress media js..just watch the js variable names below if there are errors it will be with these...

php in functions file:

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

javascript...add to the page header..wp_enqueue_scripts or to your template (do this first to make sure its working!) you'll need your element called upload_image_button or change accordinely

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

  });

template file:

    <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 return

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

or..............i came across a plugin that does this a lot better........sorry its in OOP and designed on back end but you can modify for front end! The problem with multi file uploader from WP is it required users to hit "CTRL" + click with no guidance....massive problem on front-end forms...this one you can add more guidance to easily...sorry i havent a frontend sample yet, i have yet to create :)

"Multi File Upload"

e.g.

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

save function

    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 file

    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);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top