CMS Development

ScottD22
Colaborador(a) | Parceiro Diamante
Colaborador(a) | Parceiro Diamante

Blog tags not showing on individual list items on the search results listing.

resolver

I'm looking for some help to get blog tags added to my individual search results items. Just like in the blog listing template we can add the topics/tags, I need to replicate the samen the search results page. How can I do this?


0 Avaliação positiva
1 Solução aceita
ScottD22
Solução
Colaborador(a) | Parceiro Diamante
Colaborador(a) | Parceiro Diamante

Blog tags not showing on individual list items on the search results listing.

resolver
if (tags) {
                tags.forEach(function(item,i){
                    newResult.querySelector('.hs-search-results__tags').innerHTML = tags;
                });
            }

Hey guys,

 

I've managed to fix the issuses I was having, this was my solution thanks to Stefen and a little playing around.

<p class="hs-search-results__tags"></p>
function addResult(title, url, description, featuredImage, tags) {
            var newResult = document.importNode(resultTemplate.content, true);
            function isFeaturedImageEnabled() {
                if (
                    newResult.querySelector('.hs-search-results__featured-image > img')
                ) {
                    return true;
                }
            }
            newResult.querySelector('.hs-search-results__title').innerHTML = title;
            newResult.querySelector('.hs-search-results__title').href = url;
            newResult.querySelector(
                '.hs-search-results__description'
            ).innerHTML = description;
            if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
                newResult.querySelector(
                    '.hs-search-results__featured-image > img'
                ).src=featuredImage;
            }
            if (tags) {
                tags.forEach(function(item,i){
                    newResult.querySelector('.hs-search-results__tags').innerHTML = tags;
                });
            }
            resultsSection.appendChild(newResult);
        }

 As you can see  I amended the code provided with this and it works.

 

Exibir solução no post original

10 Respostas 10
ScottD22
Solução
Colaborador(a) | Parceiro Diamante
Colaborador(a) | Parceiro Diamante

Blog tags not showing on individual list items on the search results listing.

resolver
if (tags) {
                tags.forEach(function(item,i){
                    newResult.querySelector('.hs-search-results__tags').innerHTML = tags;
                });
            }

Hey guys,

 

I've managed to fix the issuses I was having, this was my solution thanks to Stefen and a little playing around.

<p class="hs-search-results__tags"></p>
function addResult(title, url, description, featuredImage, tags) {
            var newResult = document.importNode(resultTemplate.content, true);
            function isFeaturedImageEnabled() {
                if (
                    newResult.querySelector('.hs-search-results__featured-image > img')
                ) {
                    return true;
                }
            }
            newResult.querySelector('.hs-search-results__title').innerHTML = title;
            newResult.querySelector('.hs-search-results__title').href = url;
            newResult.querySelector(
                '.hs-search-results__description'
            ).innerHTML = description;
            if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
                newResult.querySelector(
                    '.hs-search-results__featured-image > img'
                ).src=featuredImage;
            }
            if (tags) {
                tags.forEach(function(item,i){
                    newResult.querySelector('.hs-search-results__tags').innerHTML = tags;
                });
            }
            resultsSection.appendChild(newResult);
        }

 As you can see  I amended the code provided with this and it works.

 

stefen
Conselheiro(a) de destaque | Parceiro
Conselheiro(a) de destaque | Parceiro

Blog tags not showing on individual list items on the search results listing.

resolver

@ScottD22 like @dennisedson is saying, you can loop through the tags on your results page/module inside of your results loop. What I would probably do is first create a new array from all the blog post results, then add all the tags to that new array from each blog post, then de-dupe it, and finally print those tags to the page.

 

So in Javascript that would look something like this:

// create new array
var allRelevantTags = [];

// loop through all blog posts
results.forEach(function(result, index){
  // grab the blog post tags and add them to our tags array
  allRelevantTags.push.apply(allRelevantTags, result.tags)
}

// remove duplicate tags
var uniqueRelevantTags = [...new Set(allRelevantTags)];

// print each tag to page
uniqueRelevantTags.forEach(item, index) {
  document.body.appendChild(item);
}

Hope that helps!

Stefen Phelps, Community Champion, Kelp Web Developer
stefen
Conselheiro(a) de destaque | Parceiro
Conselheiro(a) de destaque | Parceiro

Blog tags not showing on individual list items on the search results listing.

resolver

@ScottD22 My solution is really for showing  all the tags outside of the posts. If you need to show the tags on each post/result it would be much easier. Basically, inside your loop where you are already looping through the results, add another loop to loop through the tags array. If you can show us the code you're using for your results I can be a better help. Thanks!

Stefen Phelps, Community Champion, Kelp Web Developer
0 Avaliação positiva
ScottD22
Colaborador(a) | Parceiro Diamante
Colaborador(a) | Parceiro Diamante

Blog tags not showing on individual list items on the search results listing.

resolver

Hey Stefen,

 

We have just cloned the search results from HubSpot in design tools. So the code if the default JS provided there. We want to show the tags on each post/result .

0 Avaliação positiva
ScottD22
Colaborador(a) | Parceiro Diamante
Colaborador(a) | Parceiro Diamante

Blog tags not showing on individual list items on the search results listing.

resolver
var hsResultsPage = function(_resultsClass) {
  function buildResultsPage(_instance) {
    var resultTemplate = _instance.querySelector(
        '.hs-search-results__template'
      ),
      resultsSection = _instance.querySelector('.hs-search-results__listing'),
      searchPath = _instance
        .querySelector('.hs-search-results__pagination')
        .getAttribute('data-search-path'),
      prevLink = _instance.querySelector('.hs-search-results__prev-page'),
      nextLink = _instance.querySelector('.hs-search-results__next-page');

    var searchParams = new URLSearchParams(window.location.search.slice(1));

    function getTerm() {
      return searchParams.get('term') || '';
    }
    function getOffset() {
      return parseInt(searchParams.get('offset')) || 0;
    }
    function getLimit() {
      return parseInt(searchParams.get('limit'));
    }
    function addResult(title, url, description, featuredImage) {
      var newResult = document.importNode(resultTemplate.content, true);
      function isFeaturedImageEnabled() {
        if (
          newResult.querySelector('.hs-search-results__featured-image > img')
        ) {
          return true;
        }
      }
      newResult.querySelector('.hs-search-results__title').innerHTML = title;
      newResult.querySelector('.hs-search-results__title').href = url;
      newResult.querySelector(
        '.hs-search-results__description'
      ).innerHTML = description;
      if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
        newResult.querySelector(
          '.hs-search-results__featured-image > img'
        ).src=featuredImage;
      }
      resultsSection.appendChild(newResult);
    }
    function fillResults(results) {
      results.results.forEach(function(result, i) {
        addResult(
          result.title,
          result.url,
          result.description,
          result.featuredImageUrl
        );
      });
    }
    function emptyPagination() {
      prevLink.innerHTML = '';
      nextLink.innerHTML = '';
    }
    function emptyResults(searchedTerm) {
      resultsSection.innerHTML =
        '<div class="hs-search__no-results"><p>Sorry. There are no results for "' +
        searchedTerm +
        '"</p>' +
        '<p>Try rewording your query, or browse through our site.</p></div>';
    }
    function setSearchBarDefault(searchedTerm) {
      var searchBars = document.querySelectorAll('.hs-search-field__input');
      Array.prototype.forEach.call(searchBars, function(el) {
        el.value = searchedTerm;
      });
    }
    function httpRequest(term, offset) {
      var SEARCH_URL = '/_hcms/search?',
        requestUrl = SEARCH_URL + searchParams + '&analytics=true',
        request = new XMLHttpRequest();

      request.open('GET', requestUrl, true);
      request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
          var data = JSON.parse(request.responseText);
          setSearchBarDefault(data.searchTerm);
          if (data.total > 0) {
            fillResults(data);
            paginate(data);
          } else {
            emptyResults(data.searchTerm);
            emptyPagination();
          }
        } else {
          console.error('Server reached, error retrieving results.');
        }
      };
      request.onerror = function() {
        console.error('Could not reach the server.');
      };
      request.send();
    }
    function paginate(results) {
      var updatedLimit = getLimit() || results.limit;

      function hasPreviousPage() {
        return results.page > 0;
      }
      function hasNextPage() {
        return results.offset <= results.total - updatedLimit;
      }

      if (hasPreviousPage()) {
        var prevParams = new URLSearchParams(searchParams.toString());
        prevParams.set(
          'offset',
          results.page * updatedLimit - parseInt(updatedLimit)
        );
        prevLink.href = '/' + searchPath + '?' + prevParams;
        prevLink.innerHTML = '&lt; Previous page';
      } else {
        prevLink.parentNode.removeChild(prevLink);
      }

      if (hasNextPage()) {
        var nextParams = new URLSearchParams(searchParams.toString());
        nextParams.set(
          'offset',
          results.page * updatedLimit + parseInt(updatedLimit)
        );
        nextLink.href = '/' + searchPath + '?' + nextParams;
        nextLink.innerHTML = 'Next page &gt;';
      } else {
        nextLink.parentNode.removeChild(nextLink);
      }
    }
    var getResults = (function() {
      if (getTerm()) {
        httpRequest(getTerm(), getOffset());
      } else {
        emptyPagination();
      }
    })();
  }
  (function() {
    var searchResults = document.querySelectorAll(_resultsClass);
    Array.prototype.forEach.call(searchResults, function(el) {
      buildResultsPage(el);
    });
  })();
};

if (
  document.attachEvent
    ? document.readyState === 'complete'
    : document.readyState !== 'loading'
) {
  var resultsPages = hsResultsPage('div.hs-search-results');
} else {
  document.addEventListener('DOMContentLoaded', function() {
    var resultsPages = hsResultsPage('div.hs-search-results');
  });
}
0 Avaliação positiva
stefen
Conselheiro(a) de destaque | Parceiro
Conselheiro(a) de destaque | Parceiro

Blog tags not showing on individual list items on the search results listing.

resolver

@ScottD22 great! Here's the couple spots you should change:

 

First, in the HTML add a new paragraph to store the tags:

      <a href="#" class="hs-search-results__title">Content Title</a>
      <p class="hs-search-results__description">Description</p>
      <p class="hs-search-results__tags"></p>

Then, in the javascript, add the tags to the addResult function:

function addResult(title, url, description, featuredImage, tags) {
      var newResult = document.importNode(resultTemplate.content, true);
      function isFeaturedImageEnabled() {
        if (
          newResult.querySelector('.hs-search-results__featured-image > img')
        ) {
          return true;
        }
      }
      newResult.querySelector('.hs-search-results__title').innerHTML = title;
      newResult.querySelector('.hs-search-results__title').href = url;
      newResult.querySelector(
        '.hs-search-results__description'
      ).innerHTML = description;
      if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
        newResult.querySelector(
          '.hs-search-results__featured-image > img'
        ).src=featuredImage;
      }
		if(tags) {
			tags.forEach(function(item,i){
				newResult.querySelector('.hs_search-results__tags').appendChild(item);
			});
		}
      resultsSection.appendChild(newResult);
    }

 Finally, in the javascript update the fillResults function with the tags:

function fillResults(results) {
      results.results.forEach(function(result, i) {
        addResult(
          result.title,
          result.url,
          result.description,
          result.featuredImageUrl,
		  result.tags
        );
      });
    }

 

Let me know if that works!

Stefen Phelps, Community Champion, Kelp Web Developer
0 Avaliação positiva
ScottD22
Colaborador(a) | Parceiro Diamante
Colaborador(a) | Parceiro Diamante

Blog tags not showing on individual list items on the search results listing.

resolver

Thanks for this Stefen, I'm now getting an error of Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node' in the console. No results are showing.

0 Avaliação positiva
ScottD22
Colaborador(a) | Parceiro Diamante
Colaborador(a) | Parceiro Diamante

Blog tags not showing on individual list items on the search results listing.

resolver

Hey Stefen,

 

We just cloned the HS search results module in design tools. We want to show tags on each post/result. Just like you do on the blog listing template.

 

 

var hsResultsPage = function(_resultsClass) {
  function buildResultsPage(_instance) {
    var resultTemplate = _instance.querySelector(
        '.hs-search-results__template'
      ),
      resultsSection = _instance.querySelector('.hs-search-results__listing'),
      searchPath = _instance
        .querySelector('.hs-search-results__pagination')
        .getAttribute('data-search-path'),
      prevLink = _instance.querySelector('.hs-search-results__prev-page'),
      nextLink = _instance.querySelector('.hs-search-results__next-page');

    var searchParams = new URLSearchParams(window.location.search.slice(1));

    function getTerm() {
      return searchParams.get('term') || '';
    }
    function getOffset() {
      return parseInt(searchParams.get('offset')) || 0;
    }
    function getLimit() {
      return parseInt(searchParams.get('limit'));
    }
    function addResult(title, url, description, featuredImage) {
      var newResult = document.importNode(resultTemplate.content, true);
      function isFeaturedImageEnabled() {
        if (
          newResult.querySelector('.hs-search-results__featured-image > img')
        ) {
          return true;
        }
      }
      newResult.querySelector('.hs-search-results__title').innerHTML = title;
      newResult.querySelector('.hs-search-results__title').href = url;
      newResult.querySelector(
        '.hs-search-results__description'
      ).innerHTML = description;
      if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
        newResult.querySelector(
          '.hs-search-results__featured-image > img'
        ).src=featuredImage;
      }
      resultsSection.appendChild(newResult);
    }
    function fillResults(results) {
      results.results.forEach(function(result, i) {
        addResult(
          result.title,
          result.url,
          result.description,
          result.featuredImageUrl
        );
      });
    }
    function emptyPagination() {
      prevLink.innerHTML = '';
      nextLink.innerHTML = '';
    }
    function emptyResults(searchedTerm) {
      resultsSection.innerHTML =
        '<div class="hs-search__no-results"><p>Sorry. There are no results for "' +
        searchedTerm +
        '"</p>' +
        '<p>Try rewording your query, or browse through our site.</p></div>';
    }
    function setSearchBarDefault(searchedTerm) {
      var searchBars = document.querySelectorAll('.hs-search-field__input');
      Array.prototype.forEach.call(searchBars, function(el) {
        el.value = searchedTerm;
      });
    }
    function httpRequest(term, offset) {
      var SEARCH_URL = '/_hcms/search?',
        requestUrl = SEARCH_URL + searchParams + '&analytics=true',
        request = new XMLHttpRequest();

      request.open('GET', requestUrl, true);
      request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
          var data = JSON.parse(request.responseText);
          setSearchBarDefault(data.searchTerm);
          if (data.total > 0) {
            fillResults(data);
            paginate(data);
          } else {
            emptyResults(data.searchTerm);
            emptyPagination();
          }
        } else {
          console.error('Server reached, error retrieving results.');
        }
      };
      request.onerror = function() {
        console.error('Could not reach the server.');
      };
      request.send();
    }
    function paginate(results) {
      var updatedLimit = getLimit() || results.limit;

      function hasPreviousPage() {
        return results.page > 0;
      }
      function hasNextPage() {
        return results.offset <= results.total - updatedLimit;
      }

      if (hasPreviousPage()) {
        var prevParams = new URLSearchParams(searchParams.toString());
        prevParams.set(
          'offset',
          results.page * updatedLimit - parseInt(updatedLimit)
        );
        prevLink.href = '/' + searchPath + '?' + prevParams;
        prevLink.innerHTML = '&lt; Previous page';
      } else {
        prevLink.parentNode.removeChild(prevLink);
      }

      if (hasNextPage()) {
        var nextParams = new URLSearchParams(searchParams.toString());
        nextParams.set(
          'offset',
          results.page * updatedLimit + parseInt(updatedLimit)
        );
        nextLink.href = '/' + searchPath + '?' + nextParams;
        nextLink.innerHTML = 'Next page &gt;';
      } else {
        nextLink.parentNode.removeChild(nextLink);
      }
    }
    var getResults = (function() {
      if (getTerm()) {
        httpRequest(getTerm(), getOffset());
      } else {
        emptyPagination();
      }
    })();
  }
  (function() {
    var searchResults = document.querySelectorAll(_resultsClass);
    Array.prototype.forEach.call(searchResults, function(el) {
      buildResultsPage(el);
    });
  })();
};

if (
  document.attachEvent
    ? document.readyState === 'complete'
    : document.readyState !== 'loading'
) {
  var resultsPages = hsResultsPage('div.hs-search-results');
} else {
  document.addEventListener('DOMContentLoaded', function() {
    var resultsPages = hsResultsPage('div.hs-search-results');
  });
}

 

 

 

0 Avaliação positiva
MarinaTakahasi
Membro | Parceiro Ouro
Membro | Parceiro Ouro

Blog tags not showing on individual list items on the search results listing.

resolver

The code works perfectly but did you know how to create each tag with link? Cause this print all tags like a sentence.

Thank you!

0 Avaliação positiva
dennisedson
Equipe de Produto da HubSpot
Equipe de Produto da HubSpot

Blog tags not showing on individual list items on the search results listing.

resolver

Hey @ScottD22 !

Great question.  If you look at the API doc for search, you will see a property called "tags".  This is what you will want to target.  

I know this fellow @stefen who is pretty good with building out things like this. 

@stefen , now that I have teed this up for you, could you show @ScottD22 how you would build this out?  

 

Thanks!

 


Join us on March 27th at 12 PM for the Digital Essentials Lab, an interactive session designed to redefine your digital strategy!
Engage with expert Jourdan Guyton to gain actionable insights, participate in live Q&A, and learn strategies to boost your business success.
Don't miss this opportunity to connect and grow—reserve your spot today!

0 Avaliação positiva