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:
1 |
<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:
1 2 3 4 5 6 |
<?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:
1 2 3 4 5 |
<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:
1 |
/<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:
1 2 3 4 5 6 7 8 9 10 |
<?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]; ?> |