WordPress.com #Posts: Get

WordPress.com #Posts: Get

translate WordPress.com #記事: 取得

Retrieves articles stored on the WordPress.com service, specifying the article (fixed page/post) by ID or Slug, and storing HTML content, excerpt data, etc. You can automate tasks such as backup and transfer operations for website management.

Auto Step icon
Configs for this Auto Step
AuthzConfU
U: Select HTTP_Authz Setting
StrConfA1
A1: Set WordPress.Com Domain (e.g. “example.com” or ID) *#{EL}
StrConfA2
A2: Set Context (e.g. “display” or “edit”)#{EL}
StrConfB1
B1: Set Post ID (e.g. “123”)#{EL}
SelectConfC1
C1: Select STRING that stores Slug (update)
SelectConfD1
D1: Select STRING that stores PostType (update)
SelectConfD2
D2: Select STRING that stores ParentID (update)
SelectConfD3
D3: Select STRING|DATETIME that stores Creation Time (update)
SelectConfD3b
D3b: Select STRING|DATETIME that stores Modified Time (update)
SelectConfD4
D4: Select STRING that stores Title (update)
SelectConfD5
D5: Select STRING that stores Excerpt (update)
SelectConfD6
D6: Select STRING that stores CategoriesCSV (update)
SelectConfD7
D7: Select STRING that stores TagsCSV (update)
SelectConfD8
D8: Select STRING that stores Contents (update)
SelectConfD9
D9: Select STRING that stores FeaturedImageURL (update)
SelectConfD9f
D9f: Select FILE that stores FeaturedImage File (update)
SelectConfD10
D10: Select STRING that stores AttachementURLs (update)
SelectConfD10f
D10f: Select FILE that stores Attachement Files (update)
StrConfB2
B2: Set Post Slug as Substitute for ID (sanitized name)#{EL}
SelectConfC2
C2: Select STRING that stores Post ID in Slug (update)
Script (click to open)
// Script Example of Business Process Automation
// for 'engine type: 3' ("GraalJS standard mode")
// cf. 'engine type: 2' ("GraalJS Nashorn compatible mode") (renamed from "GraalJS" at 20230526)

//////// START "main()" /////////////////////////////////////////////////////////////////

main();
function main(){ 

//// == Config Retrieving / 工程コンフィグの参照 ==
const strAuthzSetting     = configs.get      ( "AuthzConfU" );      // NotRequired
  engine.log( " AutomatedTask Config: Authz Setting: " + strAuthzSetting );
const strWpcomDomain      = configs.get      ( "StrConfA1" );       /// REQUIRED
  if( strWpcomDomain    === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {A1: WordPress.com domain} is empty \n" );
  }
let   strContext          = configs.get      ( "StrConfA2" );       // NotRequired
  if( strContext !== "edit" ){
      strContext          = "display";
  }
const strRequestId        = configs.get      ( "StrConfB1" );       // NotRequired
const strRequestSlug      = configs.get      ( "StrConfB2" );       // NotRequired << adv
  if( strRequestId === "" && strRequestSlug === ""){
    throw new Error( "\n AutomatedTask ConfigError:" +
             " Config {B1: Request PostId} and {B2: Request PostSlug} are both empty \n" );
  }

const strPocketSlug       = configs.getObject ( "SelectConfC1" );      // NotRequired
const strPocketResponseId = configs.getObject ( "SelectConfC2" );      // NotRequired

const strPocketType       = configs.getObject ( "SelectConfD1" );      // NotRequired
const strPocketParent     = configs.getObject ( "SelectConfD2" );      // NotRequired
const multiPocketCreationTime = configs.getObject ( "SelectConfD3" );  // NotRequired
const multiPocketModifiedTime = configs.getObject ( "SelectConfD3b" ); // NotRequired
const strPocketTitle      = configs.getObject ( "SelectConfD4" );      // NotRequired
const strPocketExcerpt    = configs.getObject ( "SelectConfD5" );      // NotRequired
const strPocketCategories = configs.getObject ( "SelectConfD6" );      // NotRequired
const strPocketTags       = configs.getObject ( "SelectConfD7" );      // NotRequired
const strPocketContent    = configs.getObject ( "SelectConfD8" );      // NotRequired
const strPocketFeaturedUrl = configs.getObject ( "SelectConfD9" );    // NotRequired
const filesPocketFeatured = configs.getObject ( "SelectConfD9f" );     // NotRequired
const strPocketAttachUrls = configs.getObject ( "SelectConfD10" );     // NotRequired
const filesPocketAttach   = configs.getObject ( "SelectConfD10f" );     // NotRequired


//// == Data Retrieving / ワークフローデータの参照 ==
// (Nothing. Some workflow data is referenced via Expression Language in Config.)


//// == Calculating / 演算 ==
/// Get a single post (by ID) or (by slug).
/// WordPress.com REST API
/// https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/posts/%24post_ID/
/// https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/posts/slug:%24post_slug/


// request1, prepare
let request1Uri = "https://public-api.wordpress.com/rest/v1.1/sites/" +
                   strWpcomDomain + "/posts/" + strRequestId;
  if( strRequestId === "" ){
    request1Uri = "https://public-api.wordpress.com/rest/v1.1/sites/" +
                   strWpcomDomain + "/posts/slug:" + strRequestSlug;
  }
let request1    = httpClient.begin(); // HttpRequestWrapper
    if ( strAuthzSetting !== "" ){
      request1    = request1.authSetting ( strAuthzSetting ); // with "Authorization: Bearer XX"
      // https://questetra.zendesk.com/hc/en-us/articles/360024574471-R2300#HttpRequestWrapper
    }
    request1    = request1.queryParam ( "context", strContext );

// request1, try
const response1     = request1.get ( request1Uri ); // HttpResponseWrapper
engine.log( " AutomatedTask ApiRequest1 Start: " + request1Uri );
const response1Code = response1.getStatusCode() + "";
const response1Body = response1.getResponseAsString() + "";
engine.log( " AutomatedTask ApiResponse Status: " + response1Code );
if( response1Code !== "200"){
  throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                    response1Code + "\n" + response1Body + "\n" );
}

// response1, parse
const response1Obj = JSON.parse( response1Body );

/* 
//engine.log( response1Body ); // debug
//engine.setDataByVarName ( "q_attachment_urls", response1Body ); // debug alt
engine.log( response1Obj.content ); // debug

{
  "ID":93865,
  "site_ID":145177791,
  "author":{
    "ID":4,
    "login":"Questetra Marketing",
    "email":false,
    "name":"Questetra Marketing",
    "first_name":"",
    "last_name":"",
    "nice_name":"questetra-marketing",
    "URL":"http:\/\/www.questetra.com",
    "avatar_URL":"https:\/\/secure.gravatar.com\/avatar\/c69ef86bcc182215d05c8d1b280fe7a6?s=96&d=identicon&r=g",
    "profile_URL":"https:\/\/gravatar.com\/c69ef86bcc182215d05c8d1b280fe7a6"
  },
  "date":"2022-10-07T14:42:26+09:00",
  "modified":"2022-10-07T14:42:27+09:00",
  "title":"Brand Guidelines",
  "URL":"https:\/\/questetra.com\/brand-guidelines\/",
  "short_URL":"https:\/\/questetra.com\/?p=93865",
  "content":"\n<p>Thank you for using ... ... ... \/p>\n",
  "excerpt":"<p>Thank you for using ... ... ... <\/a><\/p>\n",
  "slug":"brand-guidelines",
  "guid":o"https:\/\/questetra.com\/?page_id=93865",
  "status":"publish",
  "sticky":false,
  "password":"",
  "parent":false,
  "type":"page",
  "discussion":{
    "comments_open":false,
    "comment_status":"closed",
    "pings_open":false,
    "ping_status":"closed",
    "comment_count":0
  },
  "likes_enabled":true,
  "sharing_enabled":true,
  "like_count":0,
  "i_like":false,
  "is_reblogged":false,
  "is_following":true,
  "global_ID":"58123a737d7c8c377bed0a3e20595c31",
  "featured_image":"",
  "format":"standard",
  "geo":false,
  "menu_order":0,
  "page_template":"",
  "publicize_URLs":[],
  "terms":{
    "translation_priority":{}
  },
  "tags":{},
  "categories":{},
  "attachments":{},
  "attachment_count":0,
  "metadata":[{
    "id":"513607",
    "key":"amp_status",
    "value":"disabled"
  },{
    "id":"513603",
    "key":"classic-editor-remember",
    "value":"block-editor"
  }],
  "meta":{
    "links":{
      "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791\/posts\/93865",
      "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791\/posts\/93865\/help",
      "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791",
      "replies":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791\/posts\/93865\/replies\/",
      "likes":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791\/posts\/93865\/likes\/"
    }
  },
  "capabilities":{
    "publish_post":true,
    "delete_post":true,
    "edit_post":true
  },
  "other_URLs":{}
}
*/

/*
  "attachments":{
    "3441":{
      "ID":3441,
      "URL":"https:\/\/questetra.com\/wp-content\/uploads\/2014\/06\/sn2014-feedback-opening.jpg",
      "guid":"https:\/\/questetra.com\/wp-content\/uploads\/2014\/06\/sn2014-feedback-opening.jpg",
      "mime_type":"image\/jpeg",
      "width":641,
      "height":960
    },
    "3429":{
      "ID":3429,
      "URL":"https:\/\/questetra.com\/wp-content\/uploads\/2014\/06\/sn2014-feedback-performance.jpg",
      "guid":"https:\/\/questetra.com\/wp-content\/uploads\/2014\/06\/sn2014-feedback-performance.jpg",
      "mime_type":"image\/jpeg",
      "width":3920,
      "height":2204
    }
  },
  "attachment_count":2,
*/

/*
  "tags":{
    "misc":{
      "ID":35987,
      "name":"misc",
      "slug":"misc",
      "description":"",
      "post_count":3,
      "meta":{
        "links":{
          "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791\/tags\/slug:misc",
          "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791\/tags\/slug:misc\/help",
          "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791"
        }
      }
    }
  },
  "categories":{
    "Staff Blog":{
      "ID":35899,
      "name":"Staff Blog",
      "slug":"blog",
      "description":"",
      "post_count":163,
      "meta":{
        "links":{
          "self":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791\/categories\/slug:blog",
          "help":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791\/categories\/slug:blog\/help",
          "site":"https:\/\/public-api.wordpress.com\/rest\/v1.1\/sites\/145177791"
        }
      },"parent":0
    }
  },
*/

/*
{
  "error":"unauthorized",
  "message":"User cannot view post"
}
*/


let strSlug          = response1Obj.slug;
let strResponseId    = response1Obj.ID;
let strType          = response1Obj.type;
let strParent        = response1Obj.parent.toString() + ""; // false or "id"
let numCreationTime  = Date.parse ( response1Obj.date ); // millisec
let dateCreationTime = new Date ( numCreationTime );
let numModifiedTime  = Date.parse ( response1Obj.modified );
let dateModifiedTime = new Date ( numModifiedTime );
let strTitle         = response1Obj.title;
let strExcerpt       = response1Obj.excerpt; // html or text

let arrCategoryKeys  = Object.keys( response1Obj.categories );
let strCategoriesCsv = arrCategoryKeys.length ?
                       arrCategoryKeys.map ( (key) => response1Obj.categories[key].slug ).join(',') : "";
let arrTagKeys       = Object.keys( response1Obj.tags );
let strTagCsv        = arrTagKeys.length ?
                       arrTagKeys.map ( (key) => response1Obj.tags[key].slug ).join(',') : "";
let strContent       = response1Obj.content;
let strFeaturedUrl   = response1Obj.featured_image;
let arrAttachKeys    = Object.keys( response1Obj.attachments );
let strAttachUrls    = arrAttachKeys.length ?
                       arrAttachKeys.map ( (key) => response1Obj.attachments[key].URL ).join('\n') : "";


/// get files
let filesAttach      = new java.util.ArrayList();
let arrUrls = strAttachUrls === "" ? [] : strAttachUrls.split('\n');
let numLoopMax = 8; // HTTP requests must be up to 10 (M416)
engine.log( " AutomatedTask #AttachUrls: " + arrUrls.length );
if ( arrUrls.length < 8 ){ numLoopMax = arrUrls.length; }
for ( let i = 0; i < numLoopMax; i++ ) {
  // request2 - response2
  const response2 = httpClient.begin().get( arrUrls[i] );
  const response2Code = response2.getStatusCode() + ""; // JavaNum to string
  engine.log( " AutomatedTask ApiResponse2 Status: " + response2Code );
  if( response2Code !== "200"){
    throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                      response2Code + "\n" + response2.getResponseAsString() + "\n" );
  }
  const qfileTmp = new com.questetra.bpms.core.event.scripttask.NewQfile(
    getFilenameFromUri( arrUrls[i] ),
    response2.getContentType(), response2.getResponse()
  );
  filesAttach.add( qfileTmp );
}

let filesFeatured    = new java.util.ArrayList();
if ( strFeaturedUrl !== "" ) {
  // request3 - response3
  const response3 = httpClient.begin().get( strFeaturedUrl );
  const response3Code = response3.getStatusCode() + ""; // JavaNum to string
  engine.log( " AutomatedTask ApiResponse3 Status: " + response3Code );
  if( response3Code !== "200"){
    throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                      response3Code + "\n" + response3.getResponseAsString() + "\n" );
  }
  const qfileTmp = new com.questetra.bpms.core.event.scripttask.NewQfile(
    getFilenameFromUri( strFeaturedUrl ),
    response3.getContentType(), response3.getResponse()
  );
  filesFeatured.add( qfileTmp );
}



//// == Data Updating / ワークフローデータへの代入 ==
if( strPocketSlug !== null ){
  engine.setData( strPocketSlug, strSlug );
}
if( strPocketResponseId !== null ){
  engine.setData( strPocketResponseId, strResponseId );
}
if( strPocketType !== null ){
  engine.setData( strPocketType, strType );
}
if( strPocketParent !== null ){
  engine.setData( strPocketParent, strParent );
}
if( multiPocketCreationTime !== null ){
  if( multiPocketCreationTime.matchDataType( "STRING" ) ){
    engine.setData( multiPocketCreationTime, toBpmsDatetimeStr(dateCreationTime) );
  }else{
    engine.setData( multiPocketCreationTime, new java.sql.Timestamp(numCreationTime) );
  }
}
if( multiPocketModifiedTime !== null ){
  if( multiPocketModifiedTime.matchDataType( "STRING" ) ){
    engine.setData( multiPocketModifiedTime, toBpmsDatetimeStr(dateModifiedTime) );
  }else{
    engine.setData( multiPocketModifiedTime, new java.sql.Timestamp(numModifiedTime) );
  }
}
if( strPocketTitle !== null ){
  engine.setData( strPocketTitle, strTitle );
}
if( strPocketExcerpt !== null ){
  engine.setData( strPocketExcerpt, strExcerpt );
}
if( strPocketCategories !== null ){
  engine.setData( strPocketCategories, strCategoriesCsv );
}
if( strPocketTags !== null ){
  engine.setData( strPocketTags, strTagCsv );
}
if( strPocketContent !== null ){
  engine.setData( strPocketContent, strContent );
}
if( strPocketFeaturedUrl !== null ){
  engine.setData( strPocketFeaturedUrl, strFeaturedUrl );
}
if( filesPocketFeatured !== null ){
  engine.setData( filesPocketFeatured, filesFeatured );
}
if( strPocketAttachUrls !== null ){
  engine.setData( strPocketAttachUrls, strAttachUrls );
}
if( filesPocketAttach !== null ){
  engine.setData( filesPocketAttach, filesAttach );
}

} //////// END "main()" /////////////////////////////////////////////////////////////////


function toBpmsDatetimeStr( jsDate ){
  // BPMS Datetime: e.g.; "2020-04-01 23:59"

  let numLocalYear    = jsDate.getFullYear();
  let idLocalMonth    = jsDate.getMonth();
  let numLocalDate    = jsDate.getDate();
  let numLocalHours   = jsDate.getHours();
  let numLocalMinutes = jsDate.getMinutes();

  let strTmp = "";
  strTmp += numLocalYear + "-" +
            ( idLocalMonth + 1 ).toString().padStart(2, '0') + "-" +
            numLocalDate        .toString().padStart(2, '0') + " " +
            numLocalHours       .toString().padStart(2, '0') + ":" +
            numLocalMinutes     .toString().padStart(2, '0');

  return strTmp;
}


function getFilenameFromUri( strUri ){
  // Regular Expression - Named Capturing group - ES2018
  let strReUri = "^((?<protocol>[^:/?#]+):)?"; // end with ":", eg. "https:", "http:",,
      strReUri += "(//(?<host>[^/?#]*))?";     // start with "//", not include "/" "?" "#"
      strReUri += "(?<pathname>[^?#]*)";       // not include "?" "#"
      strReUri += "(\\?(?<query>[^#]*))?";     // start with "?", not include "#"
      strReUri += "(#(?<anchor>.*))?";         // start with "#"

  const regUri      = new RegExp( strReUri );
  const arrUriParts = strUri.match( regUri );
    if( arrUriParts === null ){
      throw new Error( "\n AutomatedTask UnexpectedStringError:" +
                       " No matches are found for URI regular expression \n" );
    }
  engine.log( " AutomatedTask: Protocol of Matched URI: " + arrUriParts.groups.protocol );

  /// Drill-down Path
  let strPath            = arrUriParts.groups.pathname; // eg. "/path1/path2/filename" "/filename" "/"
  let strTopDirectory    = "";
  let strLowestDirectory = "";
  let strFilename        = "";
  if( arrUriParts.groups.pathname !== undefined ){
    let arrPath          = strPath.split("/"); // "arrPath.length >= 2", because starts with "/"
    if( arrPath.length !== 2 ){
      strTopDirectory      = arrPath[ 1 ];
      strLowestDirectory   = arrPath[ arrPath.length - 2 ];
    }
    strFilename          = arrPath[ arrPath.length - 1 ];
  }
  return strFilename;
}



/*
Notes-en:
- This [Automated Step] will retrieve the Title, Excerpt, Content, Attachments, etc. of the specified article.
    - Specify by ID or Slug.
    - If both the ID and Slug are specified, ID takes precedence.
- If you place this [Automated Step] in the workflow diagram, communication will occur every time a process arrives.
    - A request is made from the Questetra BPM Suite server to the WordPress.com server.
    - The response from the WordPress.com server will be parsed, and the necessary data will be stored.
- [HTTP Authentication Settings] are required for Workflow Apps that include this [Automated Step].
    - Authorization Endpoint URL:
        - https://public-api.wordpress.com/oauth2/authorize
    - Token Endpoint URL:
        - https://public-api.wordpress.com/oauth2/token
    - Scope:
        - empty: access to one `blog` (site)
        - "global": Access to all authorized `blogs' (sites)
        - https://developer.wordpress.com/docs/oauth2/
    - Client ID, Client Secret:
        - (Retrieved from developer page ⇒ https://developer.wordpress.com/apps/ )
        - Redirect URLs: https://s.questetra.net/oauth2callback

APPENDIX-en:
- Body context
     -display mode
         - Get the display format (HTML). (Formats the output as HTML for display)
     -edit mode
         - Get formatting for editing. (Formats the output for editing.)
         - Contains Gutenberg block code (e.g: "!-- wp:paragraph --").
- Attachment Files
     - All `Attachment URLs` are stored.
     - The maximum number of `Attachments Files` that can be stored is 8 files.


Notes-ja:
- この[自動工程]は、指定記事のタイトル・抜粋文・本文・添付ファイルなどを取得します。
    - ID もしくは Slug にて指定します。
    - もし ID と Slug が両方指定された場合、ID が優先されます。
- この[自動工程]をワークフロー図に配置すれば、案件到達の度に通信が発生します。
    - Questetra BPM Suite サーバから WordPress.com サーバに対してリクエストします。
    - WordPress.com サーバからのレスポンスを解析し、必要情報を格納します。
- この[自動工程]を含むワークフローアプリには、[HTTP 認証設定]が必要です。
    - 認可エンドポイント URL:
        - https://public-api.wordpress.com/oauth2/authorize
    - トークンエンドポイント URL:
        - https://public-api.wordpress.com/oauth2/token
    - スコープ:
        - empty: 1つの `blog` (サイト)に対するアクセス
        - "global": 権限のある全ての `blog` (サイト)に対するアクセス
        - https://developer.wordpress.com/docs/oauth2/
    - クライアントID, クライアントシークレット:
        - (開発者ページから取得⇒ https://developer.wordpress.com/apps/ )
        - Redirect URLs: https://s.questetra.net/oauth2callback

APPENDIX-ja:
- 本文コンテキスト
    - display モード
        - 表示用フォーマット(HTML)を取得します。(Formats the output as HTML for display)
    - edit モード
        - 編集用フォーマットを取得します。(Formats the output for editing.)
        - Gutenberg ブロックコード(e.g: "!-- wp:paragraph --")が含まれます。
- 添付ファイル
    - `添付ファイルURLs` は全て格納されます。
    - `添付ファイル` の格納数は最大8ファイルです。
*/

Download

warning Freely modifiable JavaScript (ECMAScript) code. No warranty of any kind.
(Installing Addon Auto-Steps are available only on the Professional edition.)

Notes

Capture

Gets an article on WordPress.com service. Specify the article (fixed page/post) by ID or Slug, and store HTML content, excerpt data, etc. You can automate tasks such as backup and transfer operations for website management.

Appendix

  • Body context
    • display mode
      • Get the display format (HTML). (Formats the output as HTML for display)
    • edit mode
      • Get formatting for editing. (Formats the output for editing.)
      • Contains Gutenberg block code (e.g: “!– wp:paragraph –“).
  • Attachment Files
    • All Attachment URLs are stored.
    • The maximum number of Attachments Files that can be stored is 8 files.

See Also

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d