Wordpress.com: 統計, 表示件数の取得
Wordpress.com: 統計, 表示件数の取得 (WordPress.com: Stats, Get Views)
特定の記事が表示された回数(表示数)を取得します。Jetpack統計値から指定期間における「合計回数」および全期間通じての「総計回数」を取得します。指定期間における「日別表示数」をTSVフォーマットで取得することも可能です。
Configs
  • U: HTTP認証設定を選択してください *
  • A1: WordPress.Com ドメインをセットしてください (例 “example.com” or ID) *#{EL}
  • B1: 記事のIDをセットしてください *#{EL}
  • B2: 指定期間の開始日をセットしてください (例 “2021-06-01”) *#{EL}
  • B3: 指定範囲の終了日をセットしてください (例 “2021-06-30”) *#{EL}
  • C1: 期間の表示数合計が格納される数値型データを選択してください (更新)
  • C2: 全期間での表示数総計が格納される数値型データを選択してください (更新)
  • C3: Date-Views TSV が格納される文字列型データを選択してください (更新)
  • C4: Date-Views TSV(グラフ用) が格納される文字列型データを選択してください (更新)
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/ja/addons/wordpress-com-stats-get-views-2021/
Addonファイルのインポートは Professional でのみご利用いただけます

Notes

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

Capture

特定の記事が表示された回数(表示数)を取得します。Jetpack統計値から指定期間における「合計回数」および全期間通じての「総計回数」を取得します。指定期間における「日別表示数」をTSVフォーマットで取得することも可能です。
特定の記事が表示された回数(表示数)を取得します。Jetpack統計値から指定期間における「合計回数」および全期間通じての「総計回数」を取得します。指定期間における「日別表示数」をTSVフォーマットで取得することも可能です。

Appendix

See also

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

%d