Archive for the ‘Website Development’ Category

WordPress: Regexp and Post Views Counter Plugin

28 Nov 2015

Unfortunately, the WordPress theme I am using did not show any views for each post. While I already had an analytics account, I wanted to display the number of total unique views on my website.

I quickly found a plugin called the Post Views Counter by Dfactory. I installed it and configured it so I could use the shortcode it produced ([post-views]) in my theme.  However, the shortcode was formatted and the output contained some HTML that I simply did not need.

To demonstrate, let me print out the shortcode in this post:

The output from above (if you view source) is:

Note: The 0 will obviously be different (to match the views this post has).

I intend to use PHP regexp to get rid of all of the html and leave only the view count so I can put it into my theme. However, I first need to print out the shortcode within <pre></pre> tags because I suspect there is some whitespace in it.

So I use the follow PHP code to test:

Here we are using the WordPress function  do_shortcode to print out the content.
The results from inspecting the page source are:

Great so we now know what the actual output looks like. Now we can write the simple regexp we are going to use. I recommend using a regexp tester such as this one ( so you can test the pattern as you go.

I ended up using the following pattern:

I used the s flag so that newlines were also matched.

Finally, I performed a match to get the view count:




Posted in Website Development