使用 Wordpress API 和 Javascript 库添加带有媒体的帖子

sma*_*use 5 javascript wordpress xml-rpc posts

我想使用 API 在我的 Wordpress 博客上发帖。因为我在一个 Javascript 应用程序中,所以我会使用这种语言来做到这一点。

我进行了一些搜索,发现使用 Wordpress XML-RPC 协议的node-wpapi包。一切正常,除了发布带有媒体或特色图片的文章。

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
});
Run Code Online (Sandbox Code Playgroud)

它确实创建帖子和上传媒体,但它不会创建带有媒体的帖子。

您知道使用 JS 库创建带有媒体和特​​色图像的帖子的替代方法或更好的方法吗?

小智 4

要在创建帖子时设置特色图片,只需提供一个featured_media参数即可。例子:

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
})
Run Code Online (Sandbox Code Playgroud)

要将图像插入到帖子内容中,您可以在参数<img>中添加标签content。例子:

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

这两个版本都已针对 WordPress 5.3.2 进行了测试。我希望这有帮助!