Created
February 25, 2022 09:01
-
-
Save markhowellsmead/a9fa238a066d66e264a3e02e53f1330c to your computer and use it in GitHub Desktop.
Create a single tag, then create a post linked to that tag. Uses async/await.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const remote_domain = 'DOMAIN', // without trailing slash | |
application_password = 'APPLICATION PASSWORD', | |
username = 'USERNAME'; | |
const headers = new Headers({ | |
'Content-Type': 'application/json', | |
'Authorization': 'Basic ' + btoa(username + ':' + application_password) | |
}); | |
const makePost = async function() { | |
const tagResp = await fetch(`${remote_domain}/wp-json/wp/v2/tags`, { | |
cache: 'no-cache', | |
mode: 'cors', | |
credentials: 'include', | |
method: 'POST', | |
headers: headers, | |
body: JSON.stringify({ | |
'name': 'fudi' | |
}) | |
}); | |
const tag = tagResp.json(); | |
let tags = []; | |
if (!!tag.id) { | |
tags.push(tag.id); | |
} else if (!!tag.code && tag.code === 'term_exists') { | |
tags.push(tag.data.term_id); | |
} | |
const post_data = { | |
title: 'Post using REST API', | |
content: 'Post content using REST API', | |
status: 'publish', | |
}; | |
if (!!tags.length) { | |
post_data.tags = tags; | |
} | |
const options = { | |
cache: 'no-cache', | |
mode: 'cors', | |
credentials: 'include', | |
method: 'POST', | |
headers: headers, | |
body: JSON.stringify(post_data) | |
}; | |
fetch(`${remote_domain}/wp-json/wp/v2/posts`, options) | |
.then(data => data.json()) | |
.then(data => console.log(data.link)) | |
.catch(data => console.error(data)); | |
}; | |
makePost(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment