Skip to main contentSkip to footer

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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

Sorting search results

If you want something else than the default relevancy ranking, you can use orderby and order parameters for the search query. Orderby accepts $post variable attributes and order can be asc (ascending) or desc (descending). The most relevant attributes here are most likely post_date and comment_count. If you want to…

Related Posts:

Currently there are no related posts available.

Comment Section:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed