Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Created February 25, 2022 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhowellsmead/a9fa238a066d66e264a3e02e53f1330c to your computer and use it in GitHub Desktop.
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.
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