Search code examples
ghost-blogghost

Related Posts In Ghost Blog - Excluding Current Post


I'm using Ghost as blogging platform. When a user is reading a post I would like to show some related posts.

{{#foreach tags limit="1"}}
    {{#get "posts" filter="tags:{{slug}}" limit="6" include="author,tags" as |article|}}
        {{#foreach article}}
          ....
        {{/foreach}}
    {{/get}}
{{/foreach}}

I managed to get related posts, but I'm having issues deleting the current post from the results.

According to the Ghost Documentation I should be able to use this addition to the filter:

"+id:-{{post.id}}"

Like this:

{{#get "posts" filter="tags:{{slug}}+id:-{{post.id}}" limit="6" include="author,tags" as |article|}}

Unfortunately this is not working, {{post.id}} doesn't even prints out anything regardless the scope I am in. Simply using {{id}} instead of {{post.id}} I'm getting a value but it's the tags ID so that's not correct.

I managed to access my post ID inside the tag scope this way {{../id}} but I cannot use it in the filter this way, it's not working either.

Any idea on how to solve it would be appreciated.


Solution

  • I achieved what I needed using jQuery.

    First I get the current post id calling my function, fetching the tags for that post.

      function getCurrentPosts(id) {
    $.get(ghost.url.api('posts', {filter: 'id:' + id, include: 'tags'})).done(function (data){
          var tags = data.posts[0].tags;
          getRelatedPosts(id, tags)
    
    }).fail(function (err){
        console.log(err);
      });
    }
    

    Then I get all the posts which have the same tag and have different id from my current post id.

    function getRelatedPosts(id, tags) {
    tags = tags.map(function(obj){ 
       return  obj.slug ;
    }).join(', ');
    
    tags = '[' + tags + ']';
    
    $.get(ghost.url.api('posts', {filter: 'id:-' + id + ' +tags:' + tags, include: "author, tags" })).done(function (data){
          var posts = data.posts;
          console.log(posts.length)
          if (posts.length > 0) {
            showRelatedPosts(posts);
          }
          else{
            $('.related-section').hide();
          }
    }).fail(function (err){
         console.log(err);
      });
    }