Merge pull request #102 from Shaked/master

Override related_posts from post metadata
This commit is contained in:
Justin Mayer
2013-11-08 17:51:21 -08:00
2 changed files with 35 additions and 12 deletions

View File

@@ -17,3 +17,11 @@ For example::
{% endfor %}
</ul>
{% endif %}
You can also override related posts by using it as part of your post's meta data 'related_posts:'.
The 'related_posts:' meta data works together with your existing slugs:
related_posts: slug1,slug2,slug3...slugN
N represents the RELATED_POSTS_MAX

View File

@@ -13,23 +13,38 @@ def add_related_posts(generator):
# get the max number of entries from settings
# or fall back to default (5)
numentries = generator.settings.get('RELATED_POSTS_MAX', 5)
for article in generator.articles:
# no tag, no relation
if not hasattr(article, 'tags'):
continue
# set priority in case of forced related posts
if hasattr(article,'related_posts'):
# split slugs
related_posts = article.related_posts.split(',')
posts = []
# get related articles
for slug in related_posts:
i = 0
for a in generator.articles:
if i >= numentries: # break in case there are max related psots
break
if a.slug == slug:
posts.append(a)
i += 1
# score = number of common tags
scores = Counter()
for tag in article.tags:
scores += Counter(generator.tags[tag])
article.related_posts = posts
else:
# no tag, no relation
if not hasattr(article, 'tags'):
continue
# remove itself
scores.pop(article)
# score = number of common tags
scores = Counter()
for tag in article.tags:
scores += Counter(generator.tags[tag])
article.related_posts = [other for other, count
in scores.most_common(numentries)]
# remove itself
scores.pop(article)
article.related_posts = [other for other, count
in scores.most_common(numentries)]
def register():
signals.article_generator_finalized.connect(add_related_posts)