RSS
 

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 (http://www.phpliveregex.com/) 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:

 

 

 
4 Comments

Posted in Website Development

 

Leave a Reply

 

 
  1. Chris

    June 5, 2016 at 9:10 AM

    Really thank you for this!But how can we have the icon with the post number?Thank you!

     
    • Mohammad Ghasembeigi

      November 19, 2016 at 4:06 PM

      Simply place the number in an element with a class or id and use CSS to style it. You could also use FontAwesome to add a nice icon next to the view count.

       
  2. Developer vs. Average User: The Post Views Counter Arena - BloggInc.

    November 30, 2017 at 7:55 AM

    […] like to read more about what the plugin can do then be sure to check out Mohammad Ghasembeigi's review. And if you want more information on how to get started with it, check out Post Views Counter's […]

     
  3. Developer vs. Average User: The Post Views Counter Arena | World of WordPress

    November 30, 2017 at 3:10 PM

    […] to read more about what the plugin can do then be sure to check out Mohammad Ghasembeigi’s review. And if you want more information on how to get started with it, check out Post Views […]