ajaxwordpressseoevent-tracking

Wordpress - Trigger script when search string entered into AJAX seach field?


I have a website built in Wordpress which is using the "BWL Knowledge Base Manager" plugin which provides an AJAX search bar.

Our SEO Manager has provided us with the following tracking script which needs to be triggered when someone enters a search string into the search bar:

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'search'
'Dlv-Search': 'ger', //recorded under “s”
});
</script>

(Where, obviously, 'ger' is to be replaced with whatever the user has entered into the search field).

It turns out that I have very little idea of how to implement this. Can anyone point me in the right direction here?


Solution

  • This code looks more intimidating than it is. You should be able to add it straight to your search bar, perhaps on the keydown or onchange events. It may be cleaner if you wrap it in a function though.

    <script>
        function SO_64130617_search( el, e ){
            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
                'event': 'search'
                'Dlv-Search': el.value,
            });
        }
    </script>
    

    Then just add that function to your input on whatever event you want to handle it on:

    <input type="search" id="your-search" onchange="SO_64130617_search(this,event);" />
    

    Edit:

    Since you're unable to modify the HTML of the input, you should be able to bind an event handler to it instead. Check out this snippet:

    var search = document.querySelector('#s');
    if( search != null ){
        search.addEventListener('change', function(e){
            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
                'event': 'search',
                'Dlv-Search': this.value,
            });
    
            console.log( window.dataLayer );
        });
    }
    <input id="s" />

    Run the snippet, and the change event will log the dataLayer variable as soon as you tab away or click. The change (onchange) events require you to leave the field. You may need to use keydown or keyup or something, but that can create a LOT of function calls, at which point you'd need to look at using a typing timeout or something.