I would like to post on my Wordpress blog using API. Since I'm in a Javascript application I would do that using this language.
I have made some searches and I have found node-wpapi package, that uses Wordpress XML-RPC protocol. Everything works, except posting article with media or featured image.
const responseUploadImage = await wp.media()
.file('./tempImage.jpg')
.create({
title: 'My awesome image',
alt_text: 'an image of something awesome',
caption: 'This is the caption text',
description: 'More explanatory information'
});
const responsePostCreation = await wp.posts().create({
title: 'Your Post Title',
content: 'Your post content',
// status: 'publish'
});
const response = await wp.media().id(responseUploadImage.id).update({
post: responsePostCreation.id
});
It does create post and upload media, but it doesn't create post with media.
Do you know alternative or a better way to create posts with media and featured image with a JS 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With