Wordpress: Regexp and Post Views Counter Plugin

Website13272

Overview

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.

Post Views Counter plugin

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, you might want to print out the shortcode in a post:

[post-views]

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

<div class="post-views post-273 entry-meta">
  <span class="post-views-count">0</span>
</div>

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:

<?php
  //Get shortcode in variable
  $tmp = do_shortcode( '[post-views]');

  echo "<pre>" . $tmp . "</pre>";
?>

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

<div class="post-views post-273 entry-meta">
  <span class="post-views-count">0</span>
</div>

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:

/<div.*?>.*<span.*?>(\d*)<\/span>.*<\/div>/s

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

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

<?php
  //Get shortcode in variable
  $tmp = do_shortcode( '[post-views]');

  //Remove junk leaving only number using regexp
  preg_match_all("/<div.*?>.*<span.*?>(\d*)<\/span>.*<\/div>/s", $tmp, $results);

  //Output view count
  echo $results[1][0];
?>

Leave a comment

(required)(will not be published)(required)

Comments

Showing 2 comments from 2 commenters.

  • Display picture for Chris
    Chris

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

    Reply
    • Display picture for Mo Beigi
      Mo Beigi

      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.

      Reply