0

I can successfully create posts, set titles, content and status with Javascript/Wordpress but I am having a hard time setting the category. What is the correct syntax for setting categories with Javascript and REST API?

HTML

<select id="post_category">
  <option value="123">Bulldogs</option>
  <option value="456">Poodles</option>
  <option value="789">Pitbulls</option>
</select>

Javascript

var submitBtn = document.getElementById('submit-post-btn');

submitBtn.addEventListener('click', function(){
  var postData = {
    "title": document.getElementById('post_title').value,
    "content": document.getElementById('post_content').value,
    "status": 'publish',
    "categories": [document.getElementById('post_category').value]
  }
};

var createPost = new XMLHttpRequest();
createPost.open("POST", "https://www.example.com/wp-json/wp/v2/posts");
createPost.setRequestHeader("X-WP-Nonce", postToken.nonce);
createPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
createPost.send(JSON.stringify(postData));
createPost.onreadystatechange = function(){
    if(createPost.readyState === 4){
        if(createPost.status === 200){
            console.log("Success");
        } else {
            console.log("Error");
        }
    }
};
0

Solution was simple. Set DOM element value in JS variable instead of "document.getElementById('post_category').value" in array.

var submitBtn = document.getElementById('submit-post-btn');

submitBtn.addEventListener('click', function(){
  var categoryTerm = document.getElementById('post_category').value;
  var postData = {
  "title": document.getElementById('post_title').value,
  "content": document.getElementById('post_content').value,
  "status": 'publish',
  "categories": [categoryTerm]
  }
};
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.