Display attachments by the ID of the post being edited in the wp.media frame (frontend)
There is a button in the frontend on the post page to upload images. How do I display attachments that are attached to this post in the wp.media frame? How to intercept wp.media's AJAX request for attachments to filter attachments by post ID?
Here's what I have:
function.php
add_action('wp_enqueue_scripts','bla_bla');
function bla_bla(){
wp_enqueue_media();
wp_enqueue_script('bla_bla_bla','/script.js','',true);
}
script.js
var wpMedia;
var wp_media_post_id = wp.media.model.settings.post.id; // keeping the old post id
$('button.upload').on('click',function(event){ // file upload button in post
var btn = $(event.target);
var postID = btn.attr('post-id'), // например получим ID записи из атрибута post-id кнопки
if (wpMedia){ // if the media frame already exists, it will reopen
wpMedia.uploader.uploader.param('post_id',postID); // sets the post ID to which the attachment file will be attached
wpMedia.open(); // open wp.media
return;
}else{
wp.media.model.settings.post.id = postID; // sets the id of the wp.media post so that the loader gets the id it needs on initialization
}
var insertImage = wp.media.controller.Library.extend({ // frame options wp.media
defaults: _.defaults({
id: 'insert-image', //
title: titleForWpMediaFrame, // media uploader header
displaySettings: true, // file display settings
//filterable: 'all', // show all filters
multiple: false, // single file selection
type: ['video','audio','image','application/pdf'], // Supported file formats (DOES NOT WORK)
},wp.media.controller.Library.prototype.defaults)
});
wpMedia = wp.media.frames.wpMedia = wp.media({ // initialize the loader window (create a new media frame)
button: {text: 'Button text',}, // button name
state: 'insert-image',
states: [new insertImage()],
});
wpMedia.open(); // open wp.media
wpMedia.on('select',function(){ // handler that runs after file selection
var attachment = wpMedia.state().get('selection').first().toJSON(); // uploaded image dataset
console.log(attachment); // prints the data of the selected file to the console
wp.media.model.settings.post.id = wp_media_post_id; // recovering the main post ID
});
});
There is no script here that I tried to solve the problem because it never worked (I think this is pretty simple, but I could not find instructions on how to do it ...
Topic media-settings media-modal media-library uploads media Wordpress
Category Web