Silver Ringvee
Silver Ringvee

Reputation: 5535

WordPress upload media using Backbone JS Client

How to upload a media file using the WordPress Backbone JS Client?

I can create a new post of type media, but how to attach an actual file to it?

// Create a new media
var media = new wp.api.models.Media( { title: 'This is a demo file' } );
media.save();

Upvotes: 1

Views: 556

Answers (1)

Silver Ringvee
Silver Ringvee

Reputation: 5535

Using WP Media Library

Step 1 - Enable WP Media Library on pages you are going to use it

In functions.php or a template file

wp_enqueue_media();

Step 2 - Open the Media Library

var image = wp.media({
    title: 'Upload Image',
    type: 'image',
    multiple: false,
    button: {
        text: 'Done'
    }
}).open()

Step 3 - Get the attachment ID

image.on('select', function(e){
    var uploaded_image = image.state().get('selection').first();
    var image_id = uploaded_image.toJSON().id;
    $('input#image-id').val(image_id);
});

Step 4 - Set attachment to a post as a featured image (for example)

var image_id = parseInt($('input#image-id').val());

var post = new wp.api.models.Post( {
    title: "Post with an attachment",
    featured_media: image_id
} );

post.save();

Upvotes: 0

Related Questions