Posted on

Popular searches

This is a very common request: “How do I show the most popular searches in a widget or on a page?” Relevanssi does not have such a feature built in, and the reason for that is twofold:

First, on many sites, the most common searches are either spam or boring. On this site, I use the Relevanssi spam block tool to reduce the number of search spam. Thanks to that the top searches are not Chinese spam domains. Now the top 5 searches in the last 30 days are search, download, download/page, download/2/page, and download/2/2/page. Super interesting!

Second, displaying the most common searches allows a malicious party to influence that. They can spam the same search over and over again until it reaches the top. On a big site that takes a while, but on this site, for example, it wouldn’t take more than couple of minutes. I wouldn’t want that.

So, for these two reasons Relevanssi doesn’t ship with a “popular searches” widget. Creating one in itself would not be difficult. This code snippet, for example, creates a very simple popularsearches shortcode. The shortcode will display the five most common search terms.

add_shortcode(
  'popularsearches',
  function() {
    global $wpdb, $relevanssi_variables;
    $table            = $relevanssi_variables['log_table'];
    $popular_searches = $wpdb->get_col( "SELECT query FROM $table GROUP BY query ORDER BY COUNT(*) DESC LIMIT 5" );

    return '<ul><li>' . implode( '</li><li>', $popular_searches ) . '</li>';
  }
);

In production, this should have some kind of a profanity filter. You’d also want to put in place some kind of method where you would not log repeated identical queries at all. Use with care and consider the problems.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *