Wordpress.com: Stats, Get Views
Wordpress.com: Stats, Get Views
Gets the number of times the specified article has been viewed. Gets the subtotal for the specified period and the total for the entire period from Jetpack. It is also possible to obtain the daily values for the specified period in TSV format.
Configs
  • U: Select HTTP_Authz Setting *
  • A1: Set WordPress.Com Domain (e.g. “example.com” or ID) *#{EL}
  • B1: Set Post’s ID *#{EL}
  • B2: Set Start Date of Period (eg “2021-06-01”) *#{EL}
  • B3: Set End Date of Period (eg “2022-06-30”) *#{EL}
  • C1: Select NUM that stores Views Subtotal in Period (update)
  • C2: Select NUM that stores Views Total in Full Period (update)
  • C3: Select STRING that stores Date-Views TSV (update)
  • C4: Select STRING that stores Date-Views TSV for Chart (update)
Script (click to open)
// GraalJS Script (engine type: 2)

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

main();
function main(){ 

//// == Config Retrieving / 工程コンフィグの参照 ==
const strAuthzSetting      = configs.get      ( "AuthzConfU" );    /// REQUIRED
  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" );
  }
const strPostId            = configs.get      ( "StrConfB1" );     /// REQUIRED
  if( strPostId          === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {B1: PostID} is empty \n" );
  }
const strPeriodStart       = configs.get      ( "StrConfB2" ).substring(0, 10); /// REQUIRED
  if( strPeriodStart     === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {B2: PeriodStart} is empty \n" );
  }
const strPeriodEnd         = configs.get      ( "StrConfB3" ).substring(0, 10); /// REQUIRED
  if( strPeriodEnd       === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {B3: PeriodEnd} is empty \n" );
  }
const numPocketSubtotal    = configs.getObject( "SelectConfC1" );  // NotRequired
const numPocketTotal       = configs.getObject( "SelectConfC2" );  // NotRequired
const strPocketTsv         = configs.getObject( "SelectConfC3" );  // NotRequired
const strPocketTsvSwitched = configs.getObject( "SelectConfC4" );  // NotRequired


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


//// == Calculating / 演算 ==
/// Get Views
/// WordPress.com REST API
/// https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/post/%24post_id/
// request1, prepare
let request1Uri = "https://public-api.wordpress.com/rest/v1.1/sites/" +
                   strWpcomDomain + "/stats/post/" + strPostId;

let request1    = httpClient.begin(); // HttpRequestWrapper
    request1    = request1.authSetting( strAuthzSetting ); // with "Authorization: Bearer XX"
    request1    = request1.queryParam( "fields", "views,data" );
    // https://questetra.zendesk.com/hc/en-us/articles/360024574471-R2300#HttpRequestWrapper
// 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
/* 
engine.log( response1Body ); // debug
{
  "views":1,
  "data":[
    ["2021-06-25",0],
    ["2021-06-26",0],
    ["2021-06-27",0],
    ["2021-06-28",0],
    ["2021-06-29",1],
    ["2021-06-30",0]
  ]
}
*/
const response1Obj = JSON.parse( response1Body );
const datePeriodStart = toJsDate( strPeriodStart );
const datePeriodEnd   = toJsDate( strPeriodEnd );
let numSubtotal = 0;
let strTsv = "date\tviews\n";
let strTsvSwitchedDate = "date\t";
let strTsvSwitchedViews = "views\t";
for( let i = 0; i < response1Obj.data.length; i++ ){
  let dateTmp = toJsDate( response1Obj.data[i][0] );
  if( datePeriodStart.getTime() <= dateTmp.getTime() ){
    if( dateTmp.getTime() <= datePeriodEnd.getTime() ){
      numSubtotal         += response1Obj.data[i][1];
      strTsv              += response1Obj.data[i][0] + "\t" + response1Obj.data[i][1] + "\n";
      strTsvSwitchedDate  += response1Obj.data[i][0] + "\t";
      strTsvSwitchedViews += response1Obj.data[i][1] + "\t";
    }else{
      break;
    }
  }
}
strTsv = strTsv.slice(0, -1);                           // Remove Last "\n"
strTsvSwitchedDate  = strTsvSwitchedDate.slice(0, -1);  // Remove Last "\t"
strTsvSwitchedViews = strTsvSwitchedViews.slice(0, -1); // Remove Last "\t"
let strTsvSwitched  = strTsvSwitchedDate + "\n" + strTsvSwitchedViews;


//// == Data Updating / ワークフローデータへの代入 ==
if(               numPocketSubtotal    !== null ){
  engine.setData( numPocketSubtotal,   new java.math.BigDecimal( numSubtotal ) );
}
if(               numPocketTotal       !== null ){
  engine.setData( numPocketTotal,      new java.math.BigDecimal( response1Obj.views - 0 ) );
}
if(               strPocketTsv         !== null ){
  engine.setData( strPocketTsv,        strTsv );
}
if(               strPocketTsvSwitched !== null ){
  engine.setData( strPocketTsvSwitched, strTsvSwitched );
}


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


function toJsDate( bpmsDateOrDatetimeStr ){
  // BPMS Date:     "2020-04-01"  (subtype "Y/M" "M/D" "Y", not supported)
  // BPMS Datetime: "2020-04-01 23:59"
  let year       = 0;
  let monthIndex = 0;
  let day        = 0;
  let hours      = 0;
  let minutes    = 0;

  //  The ECMA/JavaScript Date object has a large number of methods.
  // "Date.parse" is danger (strongly discouraged)
  // - new Date("2014-11-10") // Mon Nov 10 2014 09:00:00 GMT+0900 (JST)
  // - new Date(2014, 10, 10) // Mon Nov 10 2014 00:00:00 GMT+0900 (JST)
  let arrDatetime = bpmsDateOrDatetimeStr.split(" ");
  if( arrDatetime.length === 1 ){
    let arrDateParts = arrDatetime[0].split("-");
    year       = parseInt(arrDateParts[0], 10);
    monthIndex = parseInt(arrDateParts[1], 10) - 1;
    day        = parseInt(arrDateParts[2], 10);
  }
  if( arrDatetime.length === 2 ){
    let arrDateParts = arrDatetime[0].split("-");
    let arrTimeParts = arrDatetime[1].split(":");
    year       = parseInt(arrDateParts[0], 10);
    monthIndex = parseInt(arrDateParts[1], 10) - 1;
    day        = parseInt(arrDateParts[2], 10);
    hours      = parseInt(arrTimeParts[0], 10);
    minutes    = parseInt(arrTimeParts[1], 10);
  }
  return new Date( year, monthIndex, day, hours, minutes );
}


/*
Notes-en:
- Refers Jetpack stats for your WordPress.com account.
    - WordPress.com is a service that hosts WordPress sites. It is provided by Automattic itself.
- Request is made to the "WordPress.com REST API" (WP.COM API).
    - https://developer.wordpress.com/docs/api/
    - Note: Not the "WP.REST API" for WordPress.Org.
- For the ID of the existing article, refer to the URL of the edit screen.
    - Number following `post =`
- "Date-Views TSV for Chart" is a TSV with the rows and columns switched.
    - The horizontal axis (X axis) is the date. It can be used as data for bar and line charts.
- If the date is set in the datetime format, the time part will be ignored.
    - Example: "2021-12-31 12:34" → "2021-12-31"
- If a day without logs is specified, that the number of views is considered to be 0.
    - No error will occur.

APPENDIX-en
- You can also refer to it by "Site ID" (blogid) instead of the WordPress.Com domain.
    - Site ID (blogid) is obtained from `GET v1.1/sites/example.blog/` and the "View page source".
- Setting example of "HTTP Authentication" (OAuth2)
    - Authorization Endpoint URL:
        - https://public-api.wordpress.com/oauth2/authorize
    - Token Endpoint URL:
        - https://public-api.wordpress.com/oauth2/token
    - Scope:
        - "global", "", "auth" or "media"
        - (document) https://developer.wordpress.com/docs/oauth2/
        - By default, the token will grant the application full access to a single blog.
        - Needs a "global" scope, if to access to all the blogs that users have on WordPress.com.
    - Client ID, Consumer Secret:
        - ( from https://developer.wordpress.com/apps/ )
        - Redirect URLs: https://s.questetra.net/oauth2callback

Notes-ja:
- WordPress.com アカウントの Jetpack 統計値を参照します。
    - WordPress.com は WordPress sites をホストするサービスです。Automattic 社自身が提供しています。
- "WordPress.com REST API" (WP.COM API) に対してリクエストが投げられます。
    - https://developer.wordpress.com/docs/api/
    - 注: WordPress.Org 用の "WP.REST API" ではありません。
- 既存記事のIDは、編集画面のURL等を参照してください。
    - `post=` に続く数字
- 「Date-Views TSV(グラフ用)」は「Date-Views TSV」の行と列が入れ替わったTSVです。
    - 横軸(X軸)が日付となります。棒グラフや折れ線グラフのデータとして活用できます。
- 日付が日時フォーマットで設定された場合、時刻部分は無視されます。
    - 例: "2021-12-31 12:34" → "2021-12-31"
- ログのない時期が指定された場合、当該日は 0 とみなします。
    - エラーにはなりません。

APPENDIX-ja:
- WordPress.Com ドメインの代わりに「サイトID」(blogid)で参照することも可能です。
    - サイトID(blogid)は、"`GET v1.1/sites/example.blog/`" や "ページのソース" 等から取得します。
- "HTTP認証設定" の例 (OAuth2)
    - 認可エンドポイント URL:
        - https://public-api.wordpress.com/oauth2/authorize
    - トークンエンドポイント URL:
        - https://public-api.wordpress.com/oauth2/token
    - スコープ:
        - "global", "", "auth" or "media"
        - (document) https://developer.wordpress.com/docs/oauth2/
        - デフォルトでは、1つの blog に対するアクセスが認可されます。
        - 全保有 blogs へアクセスできるようにするには "global" をセットします。
    - クライアントID, クライアントシークレット:
        - ( 開発者ページから取得してください⇒ https://developer.wordpress.com/apps/ )
        - Redirect URLs: https://s.questetra.net/oauth2callback
*/

Download

2021-06-29 (C) Questetra, Inc. (MIT License)
https://support.questetra.com/addons/wordpress-com-stats-get-views-2021/
The Add-on import feature is available with Professional edition.

Notes

  • See the Jetpack stats for your WordPress.com account.
    • WordPress.com is a service that hosts WordPress sites. It is provided by Automattic itself.
  • A request is made to the WordPress.com REST API (WP.COM API).
  • For the ID of the existing article, refer to the URL of the edit screen.
    • Number following post=
  • “Date-Views TSV (for graphs)” is a TSV with the rows and columns switched.
    • The horizontal axis (X axis) is the date. It can be used as data for bar and line charts.
  • If the date is set in the datetime format, the time part will be ignored.
    • Example: “2021-12-31 12:34” → “2021-12-31”
  • If a day without logs is specified, that the number of views is considered to be 0.
    • No error will occur.

Capture

Gets the number of the specified article has been viewed. Gets the "subtotal" for the specified period and the "total" for the entire period from Jetpack. It is also possible to obtain the daily values for the specified period in TSV format.
Gets the number of the specified article has been viewed. Gets the "subtotal" for the specified period and the "total" for the entire period from Jetpack. It is also possible to obtain the daily values for the specified period in TSV format.

Appendix

See also

1 thought on “WordPress.com: Stats, Get Views”

  1. Pingback: Wordpress.Com: Stats Views – Questetra Support

Leave a Reply

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

%d bloggers like this: