DuckDuckGo Site Search in Vanilla Forums Templates

Over at the Zettelkasten Forum, we are using a PHP forum software called Vanilla Forum”.

(Vanilla is free and open source if you host it yourself, but the creators also offer managed hosting with some additional features. I like it, it works well, and is pretty well-worn by communities all over the web.)

The default forum search is abysmal, though, so we wanted to replace it with a DuckDuckGo site-search. In most web search engines, you can use the site: prefix, as in site:christiantietze.de, to limit search results to a domain. We are already using it on the Zettelkasten main page but I couldn’t find a Vanilla plug-in in the plug-in repository to do the job.

Turns out that the default search box is implemented by adding a Smarty template engine function call. See the forum docs.

I looked at the implementation {searchbox} in /library/SmartyPlugins/function.searchbox.php. It’s implemented via the function smarty_function_searchbox – and I found out that you can add your own Smarty template functions by using the same name pattern. For {duckduckgo} I had to call my function smart_function_duckduckgo.

I put the function declaration in my themes main PHP file, the theme hooks file, at the very bottom, and that was all I had to do.

Smarty template engine function calls can have parameters. So I made the function reusable, and if you want to check it out, you can copy & paste the implementation in your template PHP file as well and tweak the parameters in your templates.

function smarty_function_duckduckgo($params, &$smarty) {
    /// Search text field placeholder value.
    $placeholder = array_key_exists('placeholder', $params)
        ? val('placeholder', $params, '', true)
        : t('SearchBoxPlaceHolder', 'Search');
    /// DuckDuckGo site-search value.
    $site = array_key_exists('site', $params)
        ? val('site', $params, '', true)
        : '';

    $form = Gdn::factory('Form');
    $result = $form->open(['action' => 'https://duckduckgo.com/?kp=-1&kl=us-en&kg=g',
            'method' => 'get', 'accept-charset' => 'utf-8',
            'role' => 'search', aria-label => 'Sitewide']).
        $form->hidden('sites', [ 'value' => $site]).
        $form->textBox('q', ['placeholder' => $placeholder,
             'name' => 'q', 'spellcheck' => 'false', 'accesskey' => '/',
             'aria-label' => t('Enter your search term.'), '
             title' => t('Enter your search term.'),
             'role' => 'searchbox', 'class' => 'InputBox js-search']).
        $form->button('Go', ['name' => '', 'arial-label' => t('Search')]).
        $form->close();
    return $result;
}

In my template, I then added this:

{duckduckgo placeholder='Search Forum' site='forum.zettelkasten.de'}

Please note that single quotes work, but double-quoted values are ignored for some reason.