使用REST API创建帖子并添加类别

时间:2018-05-25 作者:user2120881

我可以用Javascript/Wordpress成功地创建帖子、设置标题、内容和状态,但我很难设置类别。使用Javascript和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");
        }
    }
};

1 个回复
最合适的回答,由SO网友:user2120881 整理而成

解决方案很简单。在JS变量中设置DOM元素值,而不是在数组中设置“document.getElementById(\'post\\u category\').value”。

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]
  }
};

结束