Search code examples
content-management-systemghost-blogghost

How to create custom ghost api for search


Want to implement search form in ghost cms. Visitors/user must be able to search in post, author and tags. If possible some REST api which query into ghost db and return dersired result like other public ghost apis do. e.g. below api fetchs all post including tags and author.

ghost.url.api('posts', 'slug', mySlugVariable, {include: 'tags, author'});

So, I want something like this where i can pass some string and get all matched data from db.


Solution

  • I got it solved using js. Actually, i didn't find any good solution and i asked question to ghost team on their slack group they suggested me to solve this using js. So this is what i did :

    Api call

    $.get(
    ghost.url.api('posts', { include: 'tags, author' }))
    .done(function(data) {
      localStorage.setItem('posts', JSON.stringify(data));
    })
    .fail(function(err) {
      console.log(err);
    });
    

    saved all data to localStorage

    localStorage.setItem('posts', JSON.stringify(data));
    

    as user typed something in search form, I grab that search string and filter the data corresponding to that string.

    // get search results
    function getSearchResult(string) {
      var postData = JSON.parse(localStorage.getItem('posts'));
      var searchResults = postData.posts.filter(function(post) {
        return post.markdown.match(string)
          || post.title.match(string)
          || post.author.name.match(string);
      });
    
      renderSearchResults(searchResults);
    }
    

    then render result accordinging

    function renderSearchResults(posts) {
      // my render code
    }