Have you ever wished your HubSpot blog had a search feature that didn't take you off your website — looking at you, google search module 👀 — and that it would search only for blog posts? Here is how we recently accomplished this task for Quad City Safety and if you follow along, it's really not all that hard to implement yourself.
Before we dive in, let's break down what a HubSpot Blog Search consists of into its simplest form. It comes down to these three basic elements:
The first step to creating your blog search is to add an HTML module to your blog template and create a form with a single text input and a submit button like so:
The two important attributes to make note of for later are the form's action and the input's name. The action attribute's value is where you'll be taken when you submit the form. In this case, the value is the URL of the search results page (that we'll create in step 2). The name attribute's value is the parameter that will be added to the URL - which is what we'll target in our Blog loop in step 3 in order to populate the search results.
Before you can get search results, you need a place to display those search results. Create a new site page (or landing page if you don't have the Website Add-On) using whichever basic template you prefer (we'll be modifying this template in step 3). The important thing is that you create the page with the URL you used in the value of the form's action attribute. Using our example above we'll create this page with "/blog/search" as the URL.
Once you've published this page, go ahead and test your search form now. I'll wait.
Don't worry, I'll still be here.
Okay... Sure you are...
Did the form take you to the search results page? Did you see the query parameter added to the URL like so "/blog/search?query=my+search+example" but you don't see any search results?
Perfect! Now let's create those search results.
To populate the search results page with actual results, we'll need to use HubL (HubSpot's server side programming language) to loop through and display the blog posts that contain our search query.
Go ahead and edit the search results page's template (or clone it if you want to be safe) and add a HubL module where you want the search results to display on the page. In your HubL module we are going to be doing two primary things. First, we're going to use the blog_recent_posts function to pull in your most recent posts. Then, we'll filter those posts by their titles using the request.query_dict HTTP request variable to get the search query parameter from the URL. Here's the code:
Now, if you go back to your search input, you should see your matching search results:
Awesome! You just built yourself your first search engine!
If you do get fancy with it, share your work in the comments below! We love to see all the cool stuff the community builds.