Prepoblar WordPress wp_media modal con selección de imagen

32

Soy el desarrollador del complemento Advanced Custom Fields y espero que puedas ayudarme con un problema que estoy enfrentando.

Tengo un botón donde puedes editar una imagen. Este botón lanzará un modo multimedia WP 3.5 a través de la función wp_media ().

El problema es que quiero preseleccionar una imagen para que los detalles se carguen en el panel de la barra lateral.

Actualmente estoy enganchando a la devolución de llamada 'abierta' y ejecutando un código que llena esta selección, sin embargo, es un poco pesado y eficiente. Esto es lo que parece:

// _media is an object I am using

_media.frame = wp.media({
    title       :   'title',
    multiple    :   false,
    button      :   { text : 'button' }
});


// open
_media.frame.on('open',function() {


    // add class
    _media.frame.$el.closest('.media-modal').addClass('acf-media-modal acf-expanded');


    // set selection
    var selection   =   _media.frame.state().get('selection'),
        attachment  =   wp.media.attachment( id );


    attachment.fetch();
    selection.add( attachment );

});


// Finally, open the modal
_media.frame.open();

Esto funciona bien, hasta que el usuario abre otra ventana modal, selecciona la pestaña de carga y luego usa el botón de edición que he creado. Ahora el código falla completamente porque mi código se basa en que el modo modal está en el modo 'buscar'.

Encontré un código que cambiará el marco al modo de búsqueda, se ve así:

_media.frame.content.mode('browse');

Esto funciona parte del tiempo, pero luego falla el siguiente código. Al igual que se necesita algo de tiempo para procesarse antes de que el archivo adjunto se pueda agregar a la selección ...

Seguramente hay una mejor manera.

Gracias por tu ayuda. Elliot

    
pregunta Elliot Condon 13.08.2013 - 10:46

1 respuesta

3

Aquí está el script:

Estoy usando la función loadImages en la siguiente secuencia de comandos para cargar las imágenes adjuntas existentes a través de AJAX y luego simplemente pase la función con los ID de las imágenes y se abre un modo previamente poblado.

var frame,
selection = loadImages(images);

$('#stag_images_upload').on('click', function(e) {
    e.preventDefault();

var options = {
    title: '<?php _e("Create Featured Gallery", "stag"); ?>',
    state: 'gallery-edit',
    frame: 'post',
    selection: selection
};

frame = wp.media(options).open();

frame.menu.get('view').unset('cancel');
frame.menu.get('view').unset('separateCancel');
frame.menu.get('view').get('gallery-edit').el.innerHTML = '<?php _e("Edit Featured Gallery", "stag"); ?>';
frame.content.get('view').sidebar.unset('gallery'); // Hide Gallery Settings in sidebar

// when editing a gallery
overrideGalleryInsert();
frame.on( 'toolbar:render:gallery-edit', function() {
    overrideGalleryInsert();
});

frame.on( 'content:render:browse', function( browser ) {
    if ( !browser ) return;
    // Hide Gallery Settings in sidebar
    browser.sidebar.on('ready', function(){
        browser.sidebar.unset('gallery');
    });

    // Hide filter/search as they don't work
    browser.toolbar.on('ready', function(){
        if(browser.toolbar.controller._state == 'gallery-library'){
            browser.toolbar.$el.hide();
        }
    });
});

// All images removed
frame.state().get('library').on( 'remove', function() {
    var models = frame.state().get('library');
    if(models.length == 0){
        selection = false;
        $.post(ajaxurl, { ids: '', action: 'stag_save_images', post_id: stag_ajax.post_id, nonce: stag_ajax.nonce });
    }
});

function overrideGalleryInsert(){
    frame.toolbar.get('view').set({
        insert: {
            style: 'primary',
            text: '<?php _e("Save Featured Gallery", "stag"); ?>',
            click: function(){
                var models = frame.state().get('library'),
                    ids = '';

                models.each( function( attachment ) {
                    ids += attachment.id + ','
                });

                this.el.innerHTML = '<?php _e("Saving...", "stag"); ?>';

                $.ajax({
                    type: 'POST',
                    url: ajaxurl,
                    data: { 
                        ids: ids, 
                        action: 'stag_save_images', 
                        post_id: stag_ajax.post_id, 
                        nonce: stag_ajax.nonce 
                    },
                    success: function(){
                        selection = loadImages(ids);
                        $('#_stag_image_ids').val( ids );
                        frame.close();
                    },
                    dataType: 'html'
                }).done( function( data ) {
                    $('.stag-gallery-thumbs').html( data );
                    console.log(data);
                });
            }
        }
    });
}

function loadImages(images){
    if (images){
        var shortcode = new wp.shortcode({
            tag:      'gallery',
            attrs:    { ids: images },
            type:     'single'
        });

        var attachments = wp.media.gallery.attachments( shortcode );

        var selection = new wp.media.model.Selection( attachments.models, {
            props:    attachments.props.toJSON(),
            multiple: true
        });

        selection.gallery = attachments.gallery;

        selection.more().done( function() {
            // Break ties with the query.
            selection.props.set({ query: false });
            selection.unmirror();
            selection.props.unset('orderby');
        });

        return selection;
    }
    return false;
}

});

Y aquí está la función php que maneja la solicitud AJAX:

function stag_save_images(){
    if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
        return;
    }

    if ( !isset($_POST['ids']) || !isset($_POST['nonce']) || !wp_verify_nonce( $_POST['nonce'], 'stag-ajax' ) ){
        return;
    }

    if ( !current_user_can( 'edit_posts' ) ) return;

    $ids = strip_tags(rtrim($_POST['ids'], ','));
    update_post_meta($_POST['post_id'], '_stag_image_ids', $ids);

    $thumbs = explode(',', $ids);
    $thumbs_output = '';
    foreach( $thumbs as $thumb ) {
        $thumbs_output .= '<li>' . wp_get_attachment_image( $thumb, array(75,75) ) . '</li>';
    }

    echo $thumbs_output;

    die();
}
add_action( 'wp_ajax_stag_save_images', 'stag_save_images' );

function stag_metabox_scripts(){
    global $post;
    if( isset($post) ) {
        wp_localize_script( 'jquery', 'stag_ajax', array(
            'post_id' => $post->ID,
            'nonce' => wp_create_nonce( 'stag-ajax' )
        ) );
    }
}

add_action( 'admin_enqueue_scripts', 'stag_metabox_scripts' );

Acabo de copiar el fragmento de mi marco de WordPress, espero que tenga sentido.

    
respondido por el Ram Ratan Maurya 29.10.2013 - 14:34

Lea otras preguntas en las etiquetas