Last active
May 23, 2023 19:23
-
-
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
This file contains hidden or 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
<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
commented
Jan 7, 2022
via email
Hi Ivandoric,
I am grateful with your response.
Thanks for the reply very big help to me.
Take care and God Bless.
Sincerely,
Steve
…On Fri, 7 Jan 2022, 11:17 pm Ivan Dorić, ***@***.***> wrote:
***@***.**** commented on this gist.
------------------------------
@devChe <https://github.com/devChe> You need to send your data to:https://
{YOUR_DOMAIN}/wp-json/contact-form-7/v1/contact-forms/{ID_OF_YOUR_FORM}/feedback
Also you need to authenticate with Token. So to get the token you can do
something like this:
const TOKEN = typeof window !== 'undefined' &&
window.btoa('your_username:your_password')
And then you can try using fetch or axios to send that data, try something
like this:
const convertJsontoUrlencoded = (obj: any) => {
const str = []
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
str.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
}
}
return str.join('&')
}
const submitData = async () => {
setisMailSending(true)
try {
const result = await axios({
url: 'https://{YOUR_DOMAIN}/wp-json/contact-form-7/v1/contact-forms/{ID_OF_YOUR_FORM}/feedback',
headers: {
Authorization: `Basic ${TOKEN}`,
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
method: 'POST',
data: convertJsontoUrlencoded(values)
})
if (result.status === 200) {
setSubmitMessage('Your email has been sent.')
setisMailSending(false)
resetForm()
}
if (result.data.status === 'validation_failed') {
setSubmitMessage('There was an error. Try again')
setisMailSending(false)
}
setSubmitting(false)
} catch (error) {
setSubmitMessage('There was an error')
setisMailSending(false)
}
}
Try something like that, this example is from a running project. It may
not work for you fully, but you can get the basic idea of how this works.
—
Reply to this email directly, view it on GitHub
<https://gist.github.com/ca857a5596908f76dd2b39b34c993d58#gistcomment-4020068>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AMUIV2J5TTGXMYCIDTHJLH3UU37XDANCNFSM5FOMJF5Q>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
You are receiving this because you were mentioned.Message ID:
***@***.***>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment