Show the Most Popular Search Keywords

Have you ever wanted an easy way to display a list of the most popular search keywords used on your site?

Well here’s a plugin just for this occasion, the List Searches Plugin was coded by me for a client and I thought I would share it with everyone else.

search-keywords-example.PNG

To get the full experience, I will guide you from installing the plugin to processing the results and using jQuery to provide an easy submission.

To follow this guide you will need:

  1. A basic understanding of Smarty
  2. A basic understanding of jQuery

So without further ado let’s get started with installing the plugin.

First up is the plugin itself:

<?php
# List Searches Plugin
# Uses CMS Made Simple and its core Search Module authored by Ted Kulp (&copy;2012)
# Plugin Author: Robert Hunt (rgah@live.co.uk)

class list_searches
{
    /*---------------------------------------------------------
    Return array of processed search words
    ---------------------------------------------------------*/
    public function get_words($display = 'array', $limit = NULL, $include_count = false)
    {
        $words = $this->_get_words($limit, $include_count);
        if (!empty($words) && sizeof($words) > 0) {
            if ($display == 'list') {
                $tempWords = array();
                foreach ($words as $k => $v) {
                    if ($include_count)
                        array_push($tempWords, $words[$k]['word'] . ' (' . $words[$k]['count'] . ')');
                    else
                        array_push($tempWords, $words[$k]['word']);
                }
                
                $words = implode(', ', $tempWords);
                
                return $words;
            } else {
                return $words;
            }
        }
    }
    /*---------------------------------------------------------
    Get all the search words (limited if needed) and return array of results.
    ---------------------------------------------------------*/
    private function _get_words($limit = NULL, $include_count = false)
    {
        $gCms = cmsms();
        $db =& $gCms->GetDB();
        $words = array();
        
        if (!empty($limit))
            $limit = 'LIMIT ' . (int) $limit;
        else
            $limit = '';
        
        if (!empty($include_count))
            $select = '`word`, `count`';
        else
            $select = '`word`';
        
        $q = "SELECT " . $select . " FROM `" . cms_db_prefix() . "module_search_words` ORDER BY `count` DESC " . $limit;
        $db->SetFetchMode(ADODB_FETCH_ASSOC);
        $r = $db->Execute($q);
        
        if ($r && $r->RecordCount() > 0) {
            while ($row = $r->FetchRow()) {
                array_push($words, $row);
            }
            
            if (!empty($words) && sizeof($words) > 0)
                return $words;
        }
    }
}

/*---------------------------------------------------------
Process $params and assign or return completed output.
---------------------------------------------------------*/
function smarty_cms_function_list_searches($params, &$smarty)
{
    $display       = (!empty($params['display'])) ? $params['display'] : 'array';
    $limit         = (!empty($params['limit'])) ? $params['limit'] : NULL;
    $include_count = (!empty($params['include_count'])) ? true : false;
    $assign        = (!empty($params['assign'])) ? $params['assign'] : '';
    $gCms          = cmsms();
    $smarty =& $gCms->GetSmarty();
    
    $output = NULL;
    
    if (!empty($display)) {
        $list_searches = new list_searches;
        $output        = $list_searches->get_words($display, $limit, $include_count);
        
        if (!empty($output)) {
            if (!empty($assign))
                $smarty->assign($assign, $output);
            else
                return $output;
        }
    }
}

/*---------------------------------------------------------
Explanation of how the plugin works.
---------------------------------------------------------*/
function smarty_cms_help_function_list_searches()
{
?>
<h3>&nbsp;What does this tag do?</h3>
<br />
<p>
    &nbsp;This tag generates a list or array of searched keywords. It only returns values from the core Search Module released with CMS Made Simple.
</p>
<br />
<h3>&nbsp;What parameters are available</h3>
<br />
<table style="width: 50%;" cellspacing="0" cellpadding="5">
    <tbody>
        <tr>
            <th>Parameter</th><th>Description</th><th>Default</th>
        </tr>
        <tr>
            <td><code>
                display</code></td>
            <td>The type of result returned <code>
                (string) "array" OR "list"</code></td>
            <td><code>
                array</code></td>
        </tr>
        <tr>
            <td><code>
                limit</code></td>
            <td>The number to limit the results by (int)</td>
            <td>--</td>
        </tr>
        <tr>
            <td><code>
                include_count</code></td>
            <td>Whether to include the count values <code>
                (boolean) true OR false</code></td>
            <td><code>
                false</code></td>
        </tr>
        <tr>
            <td><code>
                assign</code></td>
            <td>Assign result to variable</td>
            <td>--</td>
        </tr>
    </tbody>
</table>
/*---------------------------------------------------------
Description of plugin author
---------------------------------------------------------*/
function smarty_cms_about_function_list_searches() {
?>
<p>
    Author: Robert Hunt (&copy;2012)
</p>
<p>
    This plugin is made possible by the Search Module found in the core of CMS Made Simple. The Search Module is authored by Ted Kulp (&copy;2012). You can find it on the CMS Made Simple Forge (http://dev.cmsmadesimple.org/).
</p>
<p>
    Version: 1.0
</p>
<?php
}
?>

Ok now you have the plugin, copy everything within the code box above and paste it into your favourite text editor/code editor/IDE. You will then want to save the file as “function.list_searches.php” within CMSMS’s “plugins” directory; you can find this in the root of your CMSMS install.

Not too complicated so far, is it?

The next step in our voyage of discovery is to apply the tag to our template:

{search search_method="post" resultpage="search-results"}
{list_searches limit=5 include_count=false assign="searches"}
{if count($searches)}
<div class="popSearches">
  <span class="searchTitle">Popular Searches:</span>
  {foreach from=$searches item=search name=searched}
   <a href="http://www.i-do-this.com/">{$search.word}</a>{if !$smarty.foreach.searched.last}, {/if}
  {/foreach}</div>
<!-- EOF .popSearches -->
{/if}

The first part uses the “Search” module to add an input variable to the page and then we use the plugin we just created to get the first 5 most popular search keywords and assign the result to the $searches variable.

We then check to see if the $searches variable has anything in it and apply some layout HTML.

Finally the code snippet above processes the $searches variable and applies an anchor tag with the search keyword.

For a full list of parameters for the “List Searches” plugin you can go to the admin area of your CMSMS and head over to “Extensions > Tags”. You will be presented with a list of plugins installed on your CMSMS, scroll down the list to “list_searches” and click the “Help” link.

Now we have the search form and the search word links appearing on the page the final step is to apply some jQuery; to start the search of the keyword when it is clicked:

if($('div.popSearches a').length > 0) {
 $('div.popSearches a').on('click',this,function(e) {

  e.preventDefault();
  var searchBox = $(this).parent().siblings('form');
  searchBox = searchBox.find('div.searchForm div.input');
  searchBox.find('input').val($(this).text());
  searchBox.find('.search.btn').click();
 
  return false;
 });
} 

This little snippet of jQuery checks to make sure there are search keywords on the page and then applies a “click” event handler to the search keyword links.

Because the keywords appear directly below the search form and the search form is the closest form to them I have been able to use the siblings function to find the form (it is also the only other form on the page).

Once the search form is found, the value of its input box is set to the link that was clicked and then the search form is submitted.

And that’s it! You should now have a working example (even if it isn’t styled) of searching by the most popular keywords.

NOTE: I would advise changing this piece of jQuery to suite your personal set up as this is just an example and doesn’t have any validation checks. I also advise you to test this on a staging area before going live with this plugin and functionality.

Comments