Adding posts with media using Wordpress API and Javascript library Adding posts with media using Wordpress API and Javascript library wordpress wordpress

Adding posts with media using Wordpress API and Javascript library


To set a featured image when creating a post, just provide a featured_media parameter. Example:

wp.media().file("test.jpg").create({    title: "Media Title"}).then(media => {    return wp.posts().create({        title: "Your Post Title",        content: "Fancy",        featured_media: media.id    })}).then(post => {    // Success}).catch(() => {    // Error})

To insert the image into the post content, you can put an <img> tag in the content parameter. Example:

wp.media().file("test.jpg").create({    title: "Media Title"}).then(media => {    return wp.posts().create({        title: "Hi",        content: `<img src="${media.source_url}" />`    })})

Both of these have been tested against WordPress 5.3.2.I hope this helps!