Add search suggestions to a Search facet.
Add search suggestions below a Search facet.

To add search suggestions (or “popular searches”) below a Search facet, add the following HTML directly below your Search facet.

You can remove or add links with suggested keywords as needed, but make sure to give them the same suggestion class:

<p class="search-suggestions">Popular searches: <a class="suggestion" href="#">shirt</a><a class="suggestion" href="#">hoody</a><a class="suggestion" href="#">cap</a></p>

Next, add the following snippet to your (child) theme’s functions.php. It adds a click event to the .suggestion links, so that when a user clicks a suggestion, its text is entered as a keyword in the Search facet’s input field, and the facet will immediately start filtering.

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

add_action( 'facetwp_scripts', function() { ?> <script> (function($) { document.querySelectorAll('.suggestion').forEach(function(link) { link.addEventListener('click', function(e) { e.preventDefault(); var searchtext = this.textContent; // Support multiple search facets var searchboxes = document.querySelectorAll('.facetwp-search'); searchboxes.forEach(function(searchbox) { // Prevent clicks during refresh if (!$(searchbox).prev().hasClass('f-loading')) { searchbox.value = searchtext; } }); FWP.autoload(); }); }); })(fUtil); </script> <?php }, 100 );

Next, (this is optional) add the following CSS. It will make the suggestions look like small buttons, like in the gif above. Depending on your theme’s CSS, you may need to tweak it a bit.

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

// Optional CSS add_action( 'wp_head', function() { ?> <style> .search-suggestions { margin-top: -24px; /* compensate for the 40px bottom margin below the Search facet */ font-size: 15px; } .suggestion { display: inline-block; line-height: 1em; border: 1px solid #ddd; border-radius: 3px; padding: 5px 8px; margin-left: 10px; text-decoration: none !important; color:#007cba; /* blue */ } .suggestion:hover { border-color: #007cba; /* blue */ } .suggestion:focus { outline: none !important; } </style> <?php }, 100 );

The above code can be combined with the code in the “Clear button” tutorial.

See also

Last updated: July 11, 2024