Posting Daily WordPress Statistics to Slack

I check my WordPress.com app daily to keep an eye on statistics of some of my more popular sites. It’s a nice easy way to keep track of who’s viewing what, but I wanted something a little more integrated with all my other systems.

I use Slack as a monitoring platform for my websites, apps, and servers. If something is going horribly wrong, or there’s something I need to be notified of it, I have a slack integration that lets me know. It’s an easy way to get a notification on my phone and PC that there’s something I need to fix.

It turns out that it’s actually pretty easy to connect the WordPress.com API for statistics, and a Slack app. This allows you to get fresh statistics from your site delivered to a Slack channel of your choice, whenever you want.

Here’s how to do it.

 

Connecting WordPress and Slack

Creating a Slack App

Assuming you already have a slack workspace, the first thing to do is to create a Slack App. You can do this at api.slack.com.

 

Creating a slack app screenshot

Next, you’ll want to turn on incoming webhooks by navigating to “Add features and functionality” selecting “incoming webhooks” and following the directions from there.

Slack will then give you a URL that looks something like this:

https://hooks.slack.com/services/12345/12345/12345

This will be the URL that you send your GET request to in order to post to your chosen slack workspace and channel.

Connecting the WordPress.com API

With your slack webhook created, the next thing you’ll want to do is create a WordPress.com app with your WordPress.com account. You can do this at developer.wordpress.com/apps.

Follow the steps for creating a new application. It’s all pretty basic, the only thing to keep in mind is the redirect URL. Set this to the home directory of one of your sites. During the next process (authentication), we will need to retrieve a code from the URL of this site.

Authenticating with WordPress

Now that we have both a Slack and WordPress application, we need to give the WordPress application permissions for accessing the statistics on your site. This is done through a process called OAuth. At the end of the process, we should have a non-expiring token that we can use like an API key.

We’re going to be roughly following this documentation.

  1. Grab your WordPress.com App’s Client ID (example: 12345)
  2. Get your Blog ID
    • Visit the developer console and type in /me/sites in the request bar, then hit the return button at the top right. A JSON list of sites should appear below where you can grab your ID from.
    • Example (4321)
  3. Edit the following URL with your client ID, redirect URL, and blog ID. The redirect URL is that site you entered on the Create WordPress App step.
    • Now visit that link in your browser
https://public-api.wordpress.com/oauth2/authorize?client_id=12345&redirect_uri=https://example.com&response_type=code&blog=4321

By following the steps, you will first be asked to allow your WordPress app access to your website. Next, you’ll be taken to your site to login, and finally, redirected to that redirect site you initially specified.

Important: When redirected, don’t refresh the page, we need the “code” from the URL bar.

Exchanging an OAuth Code for a Token

Now that we have been redirected to our site, we will have a short code in the URL bar at the top of your browser. It might look something like this:


https://example.com/?code=secretCode&state=

In this case, the code is “secretCode”. Remember that the ‘&’ indicates another URL parameter; it and anything after it are not a part of the code.

With your secret code, we now need to exchange it for a permanent token. We can do this with a curl request in PHP.

 



// Edit These Variables
$clientId = ""; // The client ID of your WordPress app
$redirectUrl = ""; // The redirect URL you used on your WordPress app
$clientSecretKey = ""; // The long secret key from your WordPress app admin page
$urlSecretCode = ""; // The code we got from the URL bar

$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
    'client_id' => $clientId,
    'redirect_uri' => $redirectUrl,
    'client_secret' => $clientSecretKey,
    'code' => $urlSecretCode,
    'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$secret = json_decode($auth);
$access_key = $secret->access_token;
echo $access_key;

You can place this code on your local machine, save it as a “get_code.php” script, and execute it with the command line like this.


php get_code.php

If it’s successful, it will echo back your new secret code. This is the one that you will keep forever, so don’t lose it.

 

Building The Script

Now that we have everything we need to interact with both the WordPress.com API and Slack, we can build a script in PHP that will be called by a Cron job whenever we want. Here’s the script.

 


// WordPress Monitor - Monitors a site of your choosing
$secretToken = "";
$yourWordPressSiteUrl = "example.com"; // Leave out the http/https
$slackUrl = "";

// The URL from your slack app
// Curl the WordPress.com API with the token from your WordPress app 
$options = array (
    'http' => array (
        'ignore_errors' => true,
        'header' => array (
            0 => 'authorization: Bearer ' . $secretToken,
        ),
    ),
);
$context = stream_context_create( $options );
$response = file_get_contents(
    'https://public-api.wordpress.com/rest/v1.1/sites/' . $yourWordPressSiteUrl . '/stats/',
    false,
    $context
);
$response = json_decode( $response );

// Get things of interest (Edit whatever you like)
$views_today = (string) $response->stats->views_today;

// Notify Slack
notify_slack("Today's views so far: " . $views_today);

function notify_slack($message) { 
    // Sends a CURL to slack to notify that something is happening
    $data_string = json_encode(array( "text" => $message, ));
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $slackUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string)
    ));
    curl_exec($ch);
}