Skip to content

Instantly share code, notes, and snippets.

@ivandoric
Last active May 23, 2023 19:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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>
@rodgerde
Copy link

rodgerde commented Oct 6, 2021

Hi ivandoric

I need small help, could you please suggest how can update fields via API (using HTTP POST or HTTP PUT method).
We need to update the values in those fields via an API request.
For example, we will send an API request with the JSON as the request body and this will update the values in WooCoomerce global delivery fields

image

thanks

@devChe
Copy link

devChe commented Jan 7, 2022

Hi Ivandoric,

I need some help, I have a project with next.js and wordpress graphql for my backend, I served data from wordpress and there is no problem at all but how do I send data form from my frontend next.js to wordpress contact form 7?

Please help me

Thank you
Steve

@ivandoric
Copy link
Author

@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.

@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