简体   繁体   中英

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.

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);
  });
}

I think just {{id}} would work. Just tried this and it works by removing the id of the current post but leaving the others:

{{#get "posts" limit="all" filter="id:-{{id}}"}}
    {{#foreach posts}}
        {{id}}
    {{/foreach}}
{{/get}}

Would have to be inside your {{#post}} scope though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM