Skip to content
Blog HubSpot – Search Functionality for Blogs

HubSpot – Search Functionality for Blogs

This piece of HubL code can be used to search for a keyword in a single blog or multiple blogs.

You can use the below HubL code in a separate template for search page or in the blog-listing template. In case you are going to use in the blog-listing template, you will have to tweak it a little it to show the search list or the blog list depending upon if it is a search or not.

I have added comments to the code to make it self-explanatory.

    {# Get all query params #}
    {% set querys = request.query_dict %}
    
    {# Look for the search term in the query url. eg: www.example.com?search=hubspot #}
    {% if querys.search %} {% set search = querys.search %}{% else %}{% set search = "" %}{% endif %}
    {% set search_term = search|trim %}

    {# Make sure you actually have a search term #}
    {% if search_term|length > 0 %}

        

Search Results for: {{ search_term }}

{# You can search multiple Blogs if you want, or just use 'default' #} {% set blog_ids = ['default', '0000000000', '1111111111', '2222222222' ] %} {% for blog_id in blog_ids %} {# The only limitation here is that the maximum number of recents posts #} {# that you can get from a blog using 'blog_recent_posts' method is 200. #} {% set posts = blog_recent_posts(blog_id, 200) %} {% for content in posts %} {% if search_term|lower in content.post_list_content|lower or search_term|lower in content.name|lower %}

{{ content.name }}

{{ content.post_list_content|safe|truncate(300, False, '[..]') }}

Read more ยป

{% endif %} {% endfor %} {% endfor %} {% endif %}

Hope this helps!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.