WordPress uses BackboneJS and Underscores in the admin panel. Though codex has a rich set of documentation on different WordPress topics, it lacks instructions of using these BackboneJS models in your code. So here’s a small snippet which shows you how to fetch an attachment from your WordPress blog using these models
First of all, you will have to enqueue media scripts via wp_enqueue_scripts or admin_enqueue_scripts hook. This will load all the necessary media js scripts needed for this task.
wp_enqueue_media();
And then, from your front end code you can access the attachments like this
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var attachment_id = 1234; | |
var attachment = new wp.media.model.Attachment.get(attachment_id); | |
attachment.fetch({success:function(att){ | |
if (_.contains(['png','jpg','gif','jpeg'],att.get('subtype'))) { | |
console.log(att.attributes); | |
$("<img/>").attr("src",att.attributes.sizes.thumbnail.url).appendTo($("body")); | |
} | |
}}); |
Hope you liked it 🙂