APIs & Integrations

squatchcreative
Contributor

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

I am hoping to create a more sophisticated blog post filter than what is available.  I do not want users to leave the current page when filtering the blog posts. 

 

I also do not want to simply hide/show posts with jQuery based on the topic because say I have post listings paginated by 10, then I'm really only filtering 10 posts and not all posts.  Some topics may not appear in the first 10 posts. 

 

What I am thinking is I could create a module that would accept URL parameters like so:

 

{% set topic = request.query_dict.filter %}
{% if topic %}
    {% set posts = blog_recent_tag_posts('my_blog_id', topic) %}
{% else %}
    {% set posts = blog_recent_posts('my_blog_id') %}
{% endif %}

{% for content in posts %}
  {# SHOW POST CONTENT IN HERE #}
{% endfor %}

 

and then use AJAX to call that module when the filter is used:

 

$('a#filter').click(function(e) {
    var filterVALUE = $(this).attr('filter-value');
    $.ajax({
      type: 'GET',
      url: '/modules/my-module-url',
      data: { 
        filter: filterValue
      },
      success:function(data){
        // SUCCESS LETS POST THE POSTS!
      }
    });
  });

 

but the problem I am finding is that it doesn't seem you can just call a module via AJAX.  Is that the case?  

 

Am I going about this all wrong and should I be using the Hubspot API?  Seems like I should be able to use native Hubspot functions to get posts so perhaps there is a better way to do this?  

0 Upvotes
1 Accepted solution
IWebteam
Solution
Member

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

@squatchcreativeand anyone else who is intrested, I have figured out a work around to the ajax issue without having to reload the browser.

 

`

{% set urlpath = request.path|replace('-', ' ')|replace('/', '')|replace('blog', '')|replace('tag', '')|replace(' ', '') %}
{% set my_topics = blog_topics('default', 250) %}

<!--List all topics-->
<nav id="topicMenu" class="blog-filter-options">
{% for item in my_topics %}
<a class="blog-filter-option-link {% if urlpath is string_containing item|string|lower|replace('&', '')|replace(' ', '') |replace(' ', '') %}selected{% endif %}" href="{{ blog_tag_url(group.id, item.slug) }}">{{item}}</a>
{% endfor %}
<a class="blog-filter-option-link" href="{{ group.absolute_url }}">All Topics</a>
</nav>

`

Just change the selectors below to what you need. In my case both of them were the same.

`

$( document ).ready( function() {
$('a.blog-filter-option-link').click(function(event) {
event.preventDefault();

console.log('Clicked');
$('[selector to where you want this loaded]').load($(this).attr('href') + ' [selector of section you want loaded]');

});
});

`

 

Hope this helps.

View solution in original post

9 Replies 9
IWebteam
Solution
Member

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

@squatchcreativeand anyone else who is intrested, I have figured out a work around to the ajax issue without having to reload the browser.

 

`

{% set urlpath = request.path|replace('-', ' ')|replace('/', '')|replace('blog', '')|replace('tag', '')|replace(' ', '') %}
{% set my_topics = blog_topics('default', 250) %}

<!--List all topics-->
<nav id="topicMenu" class="blog-filter-options">
{% for item in my_topics %}
<a class="blog-filter-option-link {% if urlpath is string_containing item|string|lower|replace('&', '')|replace(' ', '') |replace(' ', '') %}selected{% endif %}" href="{{ blog_tag_url(group.id, item.slug) }}">{{item}}</a>
{% endfor %}
<a class="blog-filter-option-link" href="{{ group.absolute_url }}">All Topics</a>
</nav>

`

Just change the selectors below to what you need. In my case both of them were the same.

`

$( document ).ready( function() {
$('a.blog-filter-option-link').click(function(event) {
event.preventDefault();

console.log('Clicked');
$('[selector to where you want this loaded]').load($(this).attr('href') + ' [selector of section you want loaded]');

});
});

`

 

Hope this helps.

Jaycee_Lewis
Community Manager
Community Manager

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

Hey, @IWebteam thanks for sharing your solution!

 

– Jaycee

linkedin

Jaycee Lewis

Developer Community Manager

Community | HubSpot

0 Upvotes
piersg
Key Advisor

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

Yeah, maybe HS adding more to the exceptions list e.g. GET requests to Blog posts/web pages etc. I was thinking of suggesting you use the Search API (can be used client side), but a search term is required sadly.

squatchcreative
Contributor

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

I have to say -- that is a huge disappointment.  It seems odd to have to set up an external proxy server to query my own posts after the page has loaded within a native website in Hubspot. 

 

If there was a way to execute standalone .hubl files or HubL asynchronously, something along those lines, it would certainly add much desired functionality.  

 

I appreciate the help and insight @piersg .  Hoping those features get rolled out someday.

0 Upvotes
piersg
Key Advisor

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

Ah, I forgot about the Hubspot API CORS policy. As per @Willson : The HubSpot APIs do not support support CORS AJAX requests. Making the request client-side using JavaScript would expose any authentication you're using for the request.

In order to use JavaScript/AJAX, you would need to make the request (excluding any authentication) to an external server that could then add the needed authentication and make requests to HubSpot's APIs server-side.

 

The exceptions to this rule are:

  • The Submit form data (AJAX) endpoint, which accepts CORS AJAX form submissions.
  • Most GET requests for published HubDB tables

 

The suggestion is to use a proxy server, e.g. if you have access to Hubspot Serverless functions you can do it with that.

 

squatchcreative
Contributor

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

So, looking at the docs for the CMS API V3, I should be able to just use my API key to query posts and then I have to filter through them by tag?  Is that the most efficient way?  There is no params to pass for a specific tag is there.... ?

 

Also, what needs to be done on my end to allow CORS on my own domain/application?  If I do a quick example like below I automatically get the "XMLHttpRequest at xxxx from origin xxxx has been blocked by CORS policy" error.  

 

 

$(document).ready(function() {
    $.ajax('https://api.hubapi.com/cms/v3/blogs/posts?hapikey=XXXXXXXXXXXXXXXXXX')
        .then(
            function success(response) {
                console.log(response);
            },
            function fail(data, status) {
                console.log('Request failed.  Returned status of',
                    status);
               
            }
        );
});

 

 

...but this is my natively hosted Hubspot CMS website and a module within it that is calling the API. 

 

Can this be adjusted in settings to allow my own domain or something?

 

0 Upvotes
squatchcreative
Contributor

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

Thanks for your help @dennisedson @piersg .  I kinda figured that was the route I had to go.  Seems odd to use that method when I am building out the website and that functionalilty through the native application, whereas I would normally look to use an API for an external application.  It would be great to mix server-side + client side with fetch or AJAX one day. 

 

I appreciate the insight. 

piersg
Key Advisor

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

Hi @squatchcreative, no you can't use AJAX to call a module. That's mixing server side (HubL modules) and client side (JS). I think your best bet for this would be to use the Blog Posts API, as you hinted, and then return results where the tag id is the selected filter (and state = published/ etc.). Using JS to retrieve this info can return as many posts as you want, set by the limit; you can set the limit to whatever e.g. 500 or something. You wouldn't be limited to filtering what was already on the page.

dennisedson
HubSpot Product Team
HubSpot Product Team

Set Up A Custom Filter for Blog Posts by Topic

SOLVE

@squatchcreative ,

I do believe you will have to rethink this a bit

@Anton , @stefen , @piersg how would you go about this?

0 Upvotes