I finally got this working, here is how, I'm sure there is a better way or ways I can improve, but for now it works.
First, we need to create an empty array like so...
{% set posts = [] %}
Then we need to loop through the entries, and for each entry create an array containing the entry.postDate
and the entry data. We then need to push that entry
array into the main posts
array
{% for entry in craft.entries.section('blog').limit(10) %}
{#-- We store the date reference for our custom sort function, and the entry data --#}
{% set entry = [{
'date': entry.postDate,
'data': entry
}] %}
{#-- Now we push that entry array into the posts array --#}
{% set posts = posts|merge(entry) %}
{% endfor %}
So now we've got an array containing just our craft entries. Next we need to install the Dukt Twitter plugin and the Dukt oAuth Plugin. Set them both up via the documentation and then we move on to the next step.
We now need to pull in our tweets, which with these two plugins is surprisingly easy. It looks pretty much the same as the above chunk of code, except we're executing a GET request to Twitter instead of pulling in the entries from Craft. Also, because the tweets created_at
variable is formatted in a non-standard way, we need to reformat it into the same format as the craft entry date.
{% for tweetRef in craft.twitter.get('statuses/user_timeline', {
count: 10,
}) %}
{% set tweet = [{
'date': tweetRef.created_at|date('Y-m-d'),
'data': tweetRef
}] %}
{% set posts = posts|merge(tweet) %}
{% endfor %}
So now, our posts array contains both our entries and tweets, but not in date order. With a bit of research I discovered this post which explains Twig can't sort multi-dimensional arrays. Luckily @victor_in in that post provided a solution. He has developed a plugin with improves twigs sort functionality. So download his plugin, then as he mentioned, modify the plugin to add the custom sort function.
This is the custom sort function that I used.
private function sortByDate($a, $b)
{
return strtotime($a['date']) < strtotime($b['date']);
}
I should also note that Craft was giving me an error with array('TwigBetterSortTwigExtension', 'sortByDate')
saying the class 'TwigBetterSortTwigExtension' not being found. I fixed this by replacing it with array(__CLASS__, 'sortByDate')
.
So now, we can loop through our posts array using the custom sort filter to order them by the date.
{% for entry in posts|sort('dateSort') %}
{{ entry.date }}
{% endfor %}