I had to add short of article counter to CGBlog recently, but since CGBlog ain't offering such a thing internally i decided make it UDT like.
So here is nice little script that add's simple counter based on custom field of CGBlog.
It requires two parameters:
- id = entry id
- field = witch custom field of CGBlog counter is
Example how to use:
let's say we call UDT as: cgblogcounter
Into detail template add: {cgblogcounter id=$entry->id field=''}
What this will do is add one to field value and return updated number of view's. If it meets failure, it will announce failure.
Basically that's it. Everytime someone enter your detail view of entry, it will update your counter and show new result. You may also wan't to add counter to summary template, but in that case don't use this script call. In my previous project i used:
{$entry->fieldsbyname.->value} to gain current view's without updating results.
Actual script:
Code: Select all
// Simple blog entry view's counter
global $gCms;
$db =& $gCms->GetDb();
// Check if CGBlog installed
if(!$gCms->modules['CGBlog']['object']) {
return "CGBlog module not installed!";
}
// Check if parameter id given
$id = '';
if(isset($params['id'])) {
$id = $params['id'];
} else {
return "Error: no id given";
}
// Check if parameter field given
$field = '';
if(isset($params['field'])) {
$field = $params['field'];
} else {
return "Error: no field given";
}
// Get fielddef_id from db if it exists, if failure, exit.
$query = "SELECT id FROM ".cms_db_prefix()."module_cgblog_fielddefs WHERE name=?";
$fielddef_id = $db->GetOne($query, array($field));
if(!$fielddef_id) {
return "Error: invalid field $field";
}
// Actual script. Try to update given field in given entry.
$query = "SELECT value FROM ".cms_db_prefix()."module_cgblog_fieldvals WHERE cgblog_id =? AND fielddef_id=?";
$row = $db->GetOne($query, array($id,$fielddef_id));
if($row) {
// If field dosen't consist numbers, exit.
if(!is_numeric($row)) {
return "Error: field $field exists but isn't numeric";
}
// Add one to results and update db.
$row++;
$query ="UPDATE ".cms_db_prefix()."module_cgblog_fieldvals SET value=? WHERE cgblog_id=? AND fielddef_id=?";
$db->Execute($query,array($row, $id, $fielddef_id));
return $row;
} else {
// If we didn't have anything in db yet, make new row.
$now = trim($db->DBTimeStamp(time()), "'");
$query = "INSERT INTO ".cms_db_prefix()."module_cgblog_fieldvals (cgblog_id,fielddef_id,value,create_date,modified_date) VALUES (?,?,?,?,?)";
$dbr = $db->Execute($query, array($id, $fielddef_id, 1, $now, $now));
// If this failed, its bad :(
if(!$dbr) {
die('FATAL SQL ERROR: '.$db->ErrorMsg().'<br/>QUERY: '.$db->sql);
}
return 1;
}
I hope some people found this useful, atleast i did. And best part of this script is, it let's you manipulate total view's of article

Enjoy
-Stikki-