Drafts Action Directory

Post to WordPress

Posted by Colin Walker, Last update about 16 hours ago - Unlisted

Post to WordPress directly from Drafts.

Requirements:

  • Markdown support in WordPress via Jetpack or other plugin
  • the Basic Authentication Handler plugin must be installed on your WordPress site
  • you should be using HTTPS for security (do not use this is you don’t have an SSL certificate for your site)
  • the Base64 encoder action must be installed to set up WordPress credentials

Usage

Run this action from within a draft. It will call the Base64 action to set your site URL and credentials (these will be stored as a credential object in Drafts so you only need to enter them once.)

Do not run the Base64 encoder action directly.

Install

Steps

  • includeAction

    No preview available.

  • script

    // set up the initial prompt for post status
    
    var p = Prompt.create();
    p.isCancellable = "true";
    
    var options = ["status", "standard"];
    var selectedOptions = ["status"];
    
    // single selection
    p.addSelect("s1", "Post format...", options, selectedOptions, false);
    
    p.addButton("Publish");
    p.addButton("Draft");
    
    if (p.show()) {
    
    if (p.buttonPressed == "Publish") {
      var status = "publish";
    } else {
      var status = "draft";
    }
    
    var postFormat = p.fieldValues["s1"][0];
    
    console.log(p.buttonPressed);
    
    console.log(postFormat);
    
    // Error if empty
    
    if (draft.content == "") {
      alert("The draft is empty!");
      throw new Error("The draft is empty!");
    }
    
    // define Rest API endpoint
    
    var endpoint = credential.getValue("host")+"/wp-json/wp/v2/posts";
    
    var postContent = draft.processTemplate("[[body]]");
    
    
    // create and post HTTP request
    
    var http = HTTP.create();
    var response = http.request({
      "url": endpoint,
      "method": "POST",
      "encoding": "form",
      "data": {
        "title": draft.title,
        "content": postContent,
        "status": status,
        "format": postFormat
      },
      "headers": {
        'Authorization': 'Basic '+encodedString
      }
    });
    
    console.log("Response: " + response.statusCode);
    
    // read the API response, get the post ID of the created item then view the post
    
    var responseStr = JSON.parse(response.responseText);
    var id = responseStr.id;
    
    var url = credential.getValue("host")+"/?p="+id+"&preview=true";
    
    app.openURL(url,false);
    
    } else {
      console.log("Cancelled");
    }

Options

  • After Success Archive
    Notification Error
    Log Level Info
Actions available in the Action Directory are uploaded by community members. Use appropriate caution reviewing downloaded actions before use.