有没有办法通过谷歌脚本在wordpress中添加帖子?

问题描述 投票:0回答:3

我在googlescript中有一个表单,我可以在表单中添加用户。有没有办法在该代码中实现一些行,以便脚本在wordpress页面上添加帖子?我读过这可能是通过wp_insert_post,但我不知道在我的情况下它是如何工作的。

编辑:正如斯宾塞建议我尝试通过WP REST API。

以下代码似乎正在运行.............

function httpPostTemplate() {
  // URL for target web API
  var url = 'http://example.de/wp-json/wp/v2/posts';


  // For POST method, API parameters will be sent in the
  // HTTP message payload.
  // Start with an object containing name / value tuples.
  var apiParams = {
    // Relevant parameters would go here
    'param1' : 'value1',
    'param2' : 'value2'   // etc.
  };

  // All 'application/json' content goes as a JSON string.
  var payload = JSON.stringify(apiParams);

  // Construct `fetch` params object
  var params = {
    'method': 'POST',
    'contentType': 'application/json',
    'payload': payload,
    'muteHttpExceptions' : true

  };

  var response = UrlFetchApp.fetch(url, params)

  // Check return code embedded in response.
  var rc = response.getResponseCode();
  var responseText = response.getContentText();
  if (rc !== 200) {
    // Log HTTP Error
    Logger.log("Response (%s) %s",
               rc,
               responseText );
    // Could throw an exception yourself, if appropriate
  }
  else {
    // Successful POST, handle response normally
    Logger.log( responseText );
  }
}

但我得到错误:

[16-09-28 21:24:29:475 CEST]回复(401.0){“code”:“rest_cannot_create”,“message”:“抱歉,您不能创建新帖子。”,“数据”: { “地位”:401}}

意思是:我必须先验证。我安装了插件:WP REST API - OAuth 1.0a服务器我设置了一个新用户并获得了客户端密钥和客户端用户。但是从这里我不知道该怎么做:/

wordpress google-apps-script
3个回答
0
投票

有可能的。 Wordpress有一个REST API。我可以在以下地址找到:

http://v2.wp-api.org/

您将使用UrlFetchApp服务来访问此API。文档可在以下位置找到:

https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

阅读文档并尝试编写一些代码。它会卡在你这里令你困惑的代码后,我会更新这个答案。


0
投票

谢谢你给我这些重要的链接。 <3

我安装了WP REST API和OAuth插件。在文档中写道:

在服务器上激活WP API并激活OAuth服务器插件后,您需要创建一个“客户端”。这是应用程序的标识符,包括链接到您站点所需的“密钥”和“密码”。

我找不到如何设置客户端?

根据WP API我的GoogleScriptCode中出现错误:

{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create new posts.","data":{"status":401}}

编辑:我发现它 - 它在用户/应用程序下我会试着找出来并稍后再回复你。


0
投票

您应该在标头中添加身份验证:

var headers = {
  ... ,
  'Authorization' : 'Basic ' + Utilities.base64Encode('USERNAME:PASSWORD'),
};

然后在参数中添加标题:

var params = {
  'method': 'POST',
  'headers': headers,
  'payload': JSON.stringify(payload),
  'muteHttpExceptions': true
}

然后使用UrlfetchApp.fetch

var response = UrlFetchApp.fetch("https://.../wp-json/wp/v2/posts/", params)
Logger.log(response);
© www.soinside.com 2019 - 2024. All rights reserved.