Fetch WordPress media files using BackboneJS

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.

[sourcecode language=”php”]

And then, from your front end code you can access the attachments like this

var attachment_id = 1234;
var attachment = new wp.media.model.Attachment.get(attachment_id);
if (_.contains(['png','jpg','gif','jpeg'],att.get('subtype'))) {

Hope you liked it 🙂

Leave a comment

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