DanWebb
5/2/2015 - 8:24 AM

Get any amount of latest blog posts among any amount of different blogs

Get any amount of latest blog posts among any amount of different blogs

{% comment %}
	blog_handles should contain the handles of each blog you want to pull posts from 
	seperated by commas.
{% endcomment %}
{% assign blog_handles = 'blog-1,blog-2,blog-3,blog-4,blog-5' | split: ',' %}

{% comment %}initialise the previous_article_timestamp as the current time{% endcomment %}
{% assign previous_article_timestamp = 'now' | date: '%s' %}

{% comment %}i represents the number of featured articles that will be shown{% endcomment %}
{% for i in (0..4) %}

	{% comment %}reset the latest time each time a new article needs to be found{% endcomment %}
	{% assign latest_timestamp = '' %}

	{% comment %}
		j represents the number of articles that will be checked, it should be set based on the 
		number of featured articles we want to show (i). More articles to show = more times to check.
		Remember that one blog among all the blogs could contain all the most recent articles.
	{% endcomment %}
	{% for j in (0..4) %}

      {% for blog_handle in blog_handles %}

		{% assign article_timestamp = blogs[blog_handle].articles[j].published_at | date: '%s' %}

		{% comment %}
			set the latest timestamp and article only if it was created at later than the previously
			checked articles and is not an article we've already shown.
		{% endcomment %}
		{% if article_timestamp > latest_timestamp and article_timestamp < previous_article_timestamp %}
			{% assign latest_timestamp = article_timestamp %}
			{% assign latest_article = blogs[blog_handle].articles[j] %}
		{% endif %}

      {% endfor %}

	{% endfor %}

	{% assign previous_article_timestamp = latest_article.published_at | date: '%s' %}

	{% comment %}
		here is where the article should be output, example: 
		<h1>{{ latest_article.title }}</h1>
		<h3>{{ latest_article.published_at | date: "%c" }}</h3>
		These will output in descending order, most recent article among all the blogs first.
		Alternatively we could store the article here for use elsewhere, example:
		{% if i == 0 %}{% assign featured_post_1 = latest_article %}{% endif %}
		{% if i == 1 %}{% assign featured_post_2 = latest_article %}{% endif %}
	{% endcomment %}

{% endfor %}