uploads – Mostrar archivos adjuntos por ID en un marco wp.media

Pregunta:

Estoy tratando de usar el nuevo marco de carga wp.media para una aplicación que estoy creando. He leído mucho sobre otras preguntas, publicaciones de blogs, etc.

El código que pegué a continuación ya funciona bastante bien e incluso hace algunas cosas adicionales que dejé como referencia en caso de que sea útil para alguien.

Pero hay una modificación que me gustaría incorporar: cuando se abre el marco, quiero que filtre la pantalla de la "biblioteca de medios" para mostrar solo el archivo adjunto definido por una lista de ID que proporciono.

Aquí está mi código actual:

// Uploading files
 var file_frame;

 $('.upload_attachments_button').on('click', function( event ){

event.preventDefault();

// If the media frame already exists, reopen it.
if ( file_frame ) {
  file_frame.open();
  return;
}

// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
  title: jQuery( this ).data( 'uploader_title' ),
  button: { text: jQuery( this ).data( 'uploader_button_text' ) },
  library : { type : 'image' },
  multiple: true  // Set to true to allow multiple files to be selected
});

   // When frame is open, select existing image attachments from custom field
file_frame.on( 'open', function() {

var selection = file_frame.state().get('selection');
var attachment_ids = jQuery('#attachment_ids').val().split(',');

// This is my attempt at showing only attachment with ID 275 --> but doesn't work!
file_frame.state().set( 'library', media.query({ id: 275 }) );

attachment_ids.forEach(function(id) {
  attachment = wp.media.attachment(id);
  attachment.fetch();
  selection.add( attachment ? [ attachment ] : [] );
});
 });

  // When images are selected, place IDs in hidden custom field and show thumbnails.
file_frame.on( 'select', function() {

var selection = file_frame.state().get('selection');

// Place IDs in custom field
var attachment_ids = selection.map( function( attachment ) {
  attachment = attachment.toJSON();
  return attachment.id;
}).join();
if( attachment_ids.charAt(0) === ',' ) { attachment_ids = attachment_ids.substring(1); }
$('#attachment_ids').val( attachment_ids );


// Show Thumbs
var attachment_thumbs = selection.map( function( attachment ) {
  attachment = attachment.toJSON();
  if( attachment.id != '' ) { return '<img src="' + attachment.sizes.thumbnail.url + '" id="id-' + attachment.id + '" />'; }
}).join(' ');
$('#images-feedback').show();
$('#thumbs').html(attachment_thumbs);

});

// Finally, open the modal
file_frame.open();
});


 // Place selected thumbnail ID into custom field to save as featured image 
 $(document).on('click', '#thumbs img', function() {
 $('#thumbs img').removeClass('chosen');
 var thumb_ID = $(this).attr('id').substring(3);
 $('#wpuf_featured_img').val(thumb_ID);
 $(this).addClass('chosen');
 });

Estoy intentando filtrar la visualización de la biblioteca de medios como se ve aquí, pero no da resultados:

file_frame.state().set( 'library', media.query({ id: 275 }) );

¿Alguien sabe cómo escribir la sintaxis?

Respuesta:

Siempre puede filtrar en el lado del cliente:

var query = wp.media.query();

query.filterWithIds = function(ids) {
    return _(this.models.filter(function(c) { return _.contains(ids, c.id); }));
};

var res = query.filterWithIds([6,87]); // change these to your IDs

res.each(function(v){
    console.log( v.toJSON() );
});

Descargo de responsabilidad: encontré la hermosa función filterWithIds en esta pregunta SO .

Leave a Comment

Your email address will not be published. Required fields are marked *

web tasarım