Analysing WordPress stats

It’s very useful to know what are the best posts on your blog and what are the most frequent search terms used before reaching your blog, especially when there’s a sudden spike in stats.

I’ve been using the F12 (Developer tool) in IE10 and the Network capture to figure out how to logon to WordPress. I won’t be able to explain it as I’m not a web developer but I can show how I did it in the following function 🙂

But first pls let me also introduce the awsome Get-Matches function I borrowed from Herr Dr. Tobias Weltner on this page.

function Get-Matches            
{            
    param(            
        [Parameter(Mandatory=$true)]            
        $Pattern,            
            
        [Parameter(ValueFromPipeline=$true)]            
        $InputObject            
    )            
    begin {            
        try {            
            $regex = New-Object Regex($pattern)            
        } catch {            
            Throw "Get-Matches: Pattern not correct. '$Pattern' is no valid regular expression."            
        }            
        $groups = @($regex.GetGroupNames() | Where-Object { ($_ -as [Int32]) -eq $null } | ForEach-Object { $_.toString() })            
    }            
    process {            
        foreach ($line in $InputObject)            
        {            
            foreach ($match in ($regex.Matches($line)))            
            {            
                if ($groups.Count -eq 0)            
                {            
                    ([Object[]]$match.Groups)[-1].Value            
                } else {            
                    $rv = 1 | Select-Object -Property $groups            
                    $groups | ForEach-Object { $rv.$_ = $match.Groups[$_].Value }            
                    $rv            
                }            
            }            
        }            
    }            
}

Did I say that Powershell V3 rocks!? Enjoy 😉

Function Get-WordpressStats {
[CmdletBinding()]
param(

    [Parameter()]
    [ValidateRange(-1,365)]            
    [system.int32]$Days=1,

    [parameter(Mandatory)]
    [System.String]$WPPassword=$null,

    [parameter(Mandatory)]
    [System.String]$WPUserName=$null,

    [parameter(ParameterSetName='SearchTerms')]
    [switch]$SearchTerms=$false,
    
    [parameter(ParameterSetName='PostViews')]
    [switch]$PostViews=$false
)
Begin {

    switch ($PsCmdlet.ParameterSetName)
    {
        SearchTerms {
            if ($SearchTerms) { $Action = 'searchterms' ; break}
        }
        PostViews {
            if ($PostViews) { $Action = 'postviews' ; break}
        }
        default { 
            # We will never get here because if both parametersets/switch are specified or missing
            # it will throw an error saying: 'Parameter set cannot be resolved using the specified named parameters.'
        }
    }
    $statsURI = "http://wordpress.com/wp-admin/admin-ajax.php?view=$Action&summarize&numdays=$Days&action=wpcom_load_template&template=my-stats.php"
    $UA = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.2; WOW64; Trident/6.0)'
    $HT = @{
        UserAgent = $UA
        ContentType = 'application/x-www-form-urlencoded'
        Method = 'Post'
        Body = "log=$WPUserName&pwd=$WPPassword&rememberme=forever&wp-submit=Log+In&testcookie=1"
    }

    # Authenticate
    $res1  = Invoke-WebRequest -Uri https://en.wordpress.com/wp-login.php @HT
    $res2  = Invoke-WebRequest -Uri $res1.BaseResponse.ResponseUri @HT
    $cookie1 = ($res1.BaseResponse.Headers.GetValues('Set-Cookie')[0] -replace ';.*','')
    $cookie2 =  $res2.BaseResponse.Headers.GetValues('Set-Cookie')    -split ";" -split "=\+" -match "^\S+=\S"
    $wc = New-Object System.Net.WebClient
    $wc.Headers.Add("User-Agent", $UA)
    $wc.Headers.Add("Cookie", (( $cookie1,($cookie2 -join '; ')," TESTCOOKIE=home; wordpress_eli=1; hc_post_as=wordpress") -join '; '))
}
Process {
    $result = $wc.DownloadString($statsURI)
    'Showing results for: {0}' -f ($result  | Get-Matches '<h4>(?<date>.*?)</h4>').Date
    switch($Action)
    {
        'postviews' {
            $titles =  $result  | Get-Matches '<tr((\sclass="alternate")|.?)><td\sclass="label"><span\sclass=.*?><a\shref=.*?>(?<title>.*?)</a></span></td>'
            $views  =  $result  | Get-Matches '<td\sclass="more"><a\shref=.*?><img\ssrc=.*?/></a></td><td\sclass="views">(?<views>.*?)</td></tr>'
            $i = 0
            $titles | ForEach-Object {
                New-Object -TypeName PSObject -Property @{
                    Title = $_.Title -replace "&nbsp;"," "
                    Views = $views[$i].views
                }
                $i++
             }
        }
        'searchterms' {
            $result  | Get-Matches  '(<tr((\sclass="alternate")|.?)><td\sclass="label">(?<label>.*?)</td><td\sclass="views">(?<views>.*?)</td></tr>)' | ForEach-Object -Process {
                New-Object -TypeName PSObject -Property @{
                    Terms = $_.Label
                    Views = [int]($_.Views.Trim())
                }
            }
        }
        default {}
    }
}
End {}
}
Advertisements

2 thoughts on “Analysing WordPress stats

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s