¿Usando Wordpress 3.5 Media Uploader en el meta box?

14

¿Es posible hacer esto?

Me encanta cómo funciona el nuevo cargador. Supongo que tiene que ver con una llamada jQuery como la otra manera hizo.

EDIT

Este es el código que estoy usando actualmente

jQuery(document).ready(function($) {
$('.custom_upload_image_button').click(function() {
    imageField = $(this).prev('input');
    tb_show('', 'media-upload.php?type=image&TB_iframe=true');
});
window.send_to_editor = function(html) {
    imgurl = $(html).attr('href');
    $(imageField).val(imgurl);
    tb_remove();
};
$('.clear_field').click(function() {
    var defaultImage = jQuery(this).parent().siblings('.custom_default_image').text();
    jQuery(this).parent().siblings('.custom_upload_image').val('');
    return false;
});
});
    
pregunta souporserious 12.12.2012 - 01:37

5 respuestas

9

Para comenzar, las funciones básicas y las anulaciones hasta donde sé actualmente. Puede haber mejores soluciones, pero solo tuve dos días con 3.5 aún:

// open modal - bind this to your button
    if ( typeof wp !== 'undefined' && wp.media && wp.media.editor )
        wp.media.editor.open( ##unique_id_here## );

// backup of original send function
   original_send = wp.media.editor.send.attachment;

// new send function
   wp.media.editor.send.attachment = function( a, b) {
       console.log(b); // b has all informations about the attachment
       // or whatever you want to do with the data at this point
       // original function makes an ajax call to retrieve the image html tag and does a little more
    };

// wp.media.send.to.editor will automatically trigger window.send_to_editor for backwards compatibility

// backup original window.send_to_editor
   window.original_send_to_editor = window.send_to_editor; 

// override window.send_to_editor
   window.send_to_editor = function(html) {
       // html argument might not be useful in this case
       // use the data from var b (attachment) here to make your own ajax call or use data from b and send it back to your defined input fields etc.
   }

Esta no es una respuesta de trabajo completa. Debe definir y realizar un seguimiento de sus campos de entrada por sí mismo, etc. Esto solo debe comenzar. Si tiene preguntas más concretas, solo pregunte.

Y asegúrese de reasignar las funciones originales cuando finalice su script.

Extraído de los comentarios:

  

¿Cómo puedo escuchar el evento de cierre de la caja de luz?

// add listener: 
wp.media.view.Modal.prototype.on('close', function(){ console.log('triggered close'); }
    
respondido por el ungestaltbar 12.12.2012 - 07:35
6

Aquí hay un pequeño tutorial en Cómo usar el cargador de medios WP 3.5 en las opciones de tema. Eso es lo que se me ocurrió y funciona perfecto para mí. Avísame si se te ocurre una solución mejor.

Aquí es cómo he implementado el código en mis opciones de tema:

jQuery(document).ready(function($){
  $('.stag-metabox-table .button').click(function(e){
  var send_attachment_bkp = wp.media.editor.send.attachment;
  var button = $(this);
  var id = button.attr('id').replace('_button', '');
  wp.media.editor.send.attachment = function(props, attachment){
    $("#"+id).val(attachment.url);
    wp.media.editor.send.attachment = send_attachment_bkp;
  }

  wp.media.editor.open(button);
  return false;

  });
});

Actualizar

Este código solo funciona en la página de edición posterior. Para que funcione en la página de opciones de tema, debe agregar wp_enqueue_media();

    
respondido por el Ram Ratan Maurya 13.12.2012 - 08:05
3

Estoy haciendo casi lo mismo, todavía no está listo, pero funciona:

en el php:

<input id="default_featured_image" type="text" size="100" name="default_featured_image" value="<?php echo esc_attr( $value ); ?>" />
<?php
do_action( 'media_buttons', 'default_featured_image' ); // second argument is the same as the '<input>' id

El javascript:

jQuery('#default_featured_image_button').click(function () {
    var formfield = jQuery('#default_featured_image').attr('name');
    tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
    return false;
});

window.send_to_editor = function (html) {
    var imgurl = jQuery('img', html).attr('src');
    console.log(jQuery('img', html));
    console.log(html);
    console.log(imgurl);
    // set the url as the value
    jQuery('#default_featured_image').val(imgurl);
    tb_remove();
};

Esto le permitirá cargar y enviar la url de la imagen (de cualquier tamaño) al elemento <input> .
Intento hacer esto como una configuración y funciona. Solo lo que necesito ahora es una forma confiable de enviar el ID de adjunto al <input>

    
respondido por el janw 14.12.2012 - 14:32
3

Creo que @janw ha acertado en esto, pero no pude hacer que una cosa funcionara. Jan inserta el botón de la biblioteca de medios usando:

do_action( 'media_buttons', 'default_featured_image' );

y luego anula la acción predeterminada usando:

jQuery('#default_featured_image_button').click(function () {...

El problema con el que me encontré es que al insertar un botón de medios de esta manera no se asigna una identificación de "default_featured_image_button" al enlace. De hecho, no agrega ningún ID en el enlace insertado. Así que esto es lo que hice para que funcione.

Agregué esta línea a mi función de devolución de llamada de meta caja justo después de mi campo de entrada:

<input id="upload_logo_button" type="button" value="Media Library Image" class="button-secondary" />

Luego coloqué en cola mi archivo jquery personalizado y el archivo css thickbox, también en mi archivo functions.php, usando:

add_action('admin_enqueue_scripts', 'jhsir_load_image_set_js');

function jhsir_load_image_set_js() {
    wp_enqueue_script( 'jhsir_image_set_script', get_stylesheet_directory_uri() . '/js/image-set.js', array('jquery','media-upload','thickbox') );
    wp_enqueue_style( 'thickbox' );
}

Finalmente, mi archivo image-set.js incluyó lo siguiente:

jQuery(document).ready(function($) {

    var formfield = null;

    $('#upload_logo_button, #upload_background_button').click(function() {

        $('html').addClass('Image');

        formfield = $(this).prev('input').attr('name');  
        formfield_id = $(this).prev('input').attr('id'); 

        tb_show( '', 'media-upload.php?type=image&TB_iframe=true' );
        return false;
    });

    // user inserts file into post.
    // only run custom if user started process using the above process
    // window.send_to_editor(html) is how wp normally handles the received data

    window.original_send_to_editor = window.send_to_editor;
    window.send_to_editor = function( html ) {
        var fileurl;

        if(formfield != null) {
            fileurl = $( 'img', html).attr('src');

            $( "#" + formfield_id ).val(fileurl);

            tb_remove();

            $('html').removeClass('Image');
            formfield = null;
        } else {
            window.original_send_to_editor(html);
        }
    };
});

Observará que usé variables para almacenar el nombre y la identificación del campo de entrada que está justo antes del enlace que llama a jQuery. De esa manera, este código se puede usar repetidamente en la misma página. Solo deberías asignar una clase a todos los botones o usar los ID individuales para los botones de tu jQuery como lo hice yo. Espero que esto ayude a alguien como la respuesta de Jan a mí.

    
respondido por el MatthewLee 13.03.2013 - 20:48
0

Sé que esta es una publicación antigua, pero solo quiero compartir mis conclusiones:

Para abrir el editor de medios, llamamos a esta función

wp.media.editor.open();

el editor de medios básicamente buscará el editor tinyMCE ( window.tinymce ), luego Quicktags ( window.QTags ), para pasarle el contenido.

Para mi enfoque para obtener el contenido, asigné window.QTags con un objeto personalizado, que tiene un método insertContent() :

var newObject = {
  insertContent: function(html){
    // to extract the image source
    $(html).find('img').attr('src');
  }
}

// assign the newObject to window.QTags property
window.QTags = newObject;

Referencia: phpxref

    
respondido por el user3323765 28.11.2015 - 12:00

Lea otras preguntas en las etiquetas