by
KK » Mon Feb 23, 2015 8:44 pm
@atisz
I think for a simple 'page-hit counter', like the one you want, we don't need a dedicated addon. it can be done using plain Couch code.
Here is how I made one (I'll assume we are building it for a template named 'blog.php') -
1. Define the following editable region in the template
<cms:template title='Blog' clonable='1'>
..
..
<cms:editable label='Page hits' name='page_hits' type='text' search_type='integer' />
</cms:template>
2. Place the following code in the template's page-view
- Code: Select all
<cms:if k_is_page>
<cms:no_cache />
<cms:php>
// identify bots
global $CTX;
if( isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT']) ){
$CTX->set( 'is_bot', '1', 'global' );
}
</cms:php>
<cms:if "<cms:not is_bot />">
<cms:db_persist
_masterpage=k_template_name
_page_id=k_page_id
_mode='edit'
page_hits="<cms:add page_hits '1' />"
/>
</cms:if>
</cms:if>
The code above simply increments the hit counter by 1 every time the page is accessed (trying not to do so for bots).
Please notice that we are using cms:no_cache to prevent the page-views from being cached as, obviously, the code will not work.
And that is all that is needed.
On the frontend, we can use the 'page_hits' editable region with cms:pages tag e.g. the following will display the top 5 most viewed blog posts-
- Code: Select all
<cms:pages masterpage='blog.php' orderby='page_hits' limit='5'>
...
</cms:pages>
Does this help?