Skip to content

Instantly share code, notes, and snippets.

@ivandoric
Last active May 23, 2023 19:23
Show Gist options
  • Save ivandoric/ca857a5596908f76dd2b39b34c993d58 to your computer and use it in GitHub Desktop.
Save ivandoric/ca857a5596908f76dd2b39b34c993d58 to your computer and use it in GitHub Desktop.
WordPress Rest API Add Posts From Frontend (Video Tutorials Notes) - Check out the video: https://www.youtube.com/watch?v=_w4Ok-lI48g
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="<?php echo get_template_directory_uri() ?>/style.css">
<title>Watch Learn Theme</title>
</head>
<body>
<h1>Hello World</h1>
<button class="js-add-post">Add post</button>
<script>
fetch('http://wp-rest.test/wp-json/wp/v2/posts').then(function(response){
return response.json()
}).then(function(posts){
console.log(posts)
});
fetch('http://wp-rest.test/wp-json/jwt-auth/v1/token',{
method: "POST",
headers:{
'Content-Type': 'application/json',
'accept': 'application/json',
},
body:JSON.stringify({
username: 'admin',
password: 'test123'
})
}).then(function(response){
return response.json()
}).then(function(user){
console.log(user.token)
localStorage.setItem('jwt', user.token)
});
function addPost() {
fetch('http://wp-rest.test/wp-json/wp/v2/product',{
method: "POST",
headers: {
'Content-Type': 'application/json',
'accept': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('jwt')}`
},
body:JSON.stringify({
title: 'Add posts from the frontend',
content: 'This is the way to add posts from your frontend.',
status: 'publish'
})
}).then(function(response){
return response.json()
}).then(function(post){
console.log(post)
});
}
const addPostButton = document.querySelector('.js-add-post')
addPostButton.addEventListener('click', () => addPost())
</script>
</body>
</html>
@devChe
Copy link

devChe commented Jan 7, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment