How does TAG cloud works in Codefight CMS?

Posted by Damodar Bashyal on April 06, 2009

 

How does TAG cloud works in Codefight CMS?

Admin/Modules/Pages/Controllers/Pages.php:

In admin when creating page, if tags are set split tags separated with commas. Then clean up every tag for tag-key as $tag. Then insert the tags into tag clouds table.

<?php
if(isset($pages_tags))
{
$pages_tags = split(',',$pages_tags);
if(is_array($pages_tags) && count($pages_tags) > 0)
foreach($pages_tags as $v)
{
//clean tag
$tag = $this->data_model->link_clean($v);
//add|increment tag count
$this->data_model->tag_cloud_add($tag, 'page', $v);
//insert tags to tags table
$this->db->insert('pages_tags', array('pages_id' => $page_id, 'tags' => $tag));
}
}
?>
Admin/Models/Data_model.php

Link Clean:
<?php
function link_clean($segment = false)
{
//remove invalid characters with spaces, trim it and replace spaces with dashes
return preg_replace('/\s+?/','-',trim(preg_replace('/[^a-z0-9]+/i',' ',strtolower($segment))));
}
?>
Insert Tags:
<?php
function tag_cloud_add ($tag = '', $type = 'page', $title='')
{
if(!empty($tag))
{
$this->db->where(array('tag' => $tag, 'type' => $type));
$count = $this->db->count_all_results('tags_cloud');

//if tag found increment count by 1 else insert as new
if($count) 
{
$this->db->set('count', 'count+1', FALSE);
$this->db->where(array('tag' => $tag, 'type' => $type));
$this->db->update('tags_cloud');
}
else
{
$this->db->insert('tags_cloud', array('tag' => $tag, 'type' => $type, 'title' => $title));
}
}
}
?>

OK, we inserted tags into tag cloud. Now its time to get the cloud in the frontend.

Frontend/Views/Templates/Core/Blocks/Tag_cloud.php
<?php
//Get Tag Cloud
$cloud = $this->data_model->tag_cloud_get();

//Shuffle the Cloud
shuffle($cloud);

//Display Cloud Tags
foreach($cloud as $c)
{
?>
<a class="<?php echo $c['class']; ?>" href="<?php echo site_url('tag/' . $c['type'] . '/' . $c['tag']); ?>" title="Total posts for <?php echo trim($c['title']); ?> is <?php echo $c['count']; ?>"><?php echo trim($c['title']); ?></a ><?php
}
Frontend/Models/Data_model.php
<?php
function tag_cloud_get($type=false)
{
if($type)
$this->db->where('type', $type);
$this->db->order_by('count', 'desc');
$this->db->limit(20);
$query = $this->db->get('tags_cloud');

$tag = $query->result_array();
foreach($tag as $k => $v) {
$tag[$k]['class'] = "cloud$k";
}
return $tag;
}
?>

So, the tags are sorted by tags count in descending order and we take first 20 and display them in our tag cloud block.

There must be more better ways to do it, but it works for me now. Also, i have set anchor class as cloud1, cloud2, cloud3 etc, so we can give size, color etc to our tags as we like.

Thats it!!!

Happy Tag Clouding :)

 
not published on website


QR Code: How does TAG cloud works in Codefight CMS?