I want to create a script (javascript/jQuery) for a WordPress website which allow me to have latest posts from multiple Facebook pages. I don't want the posts to be ordered by account, but be mixed all together, ordered by created_time. I've already search for plugin, I don't want a WP plugin.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>FaceBook Posts</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function fbFetch(){
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/footengo31/posts?access_token=XXX&limit=5&callback=?";
var url2 = "https://graph.facebook.com/footengo01/posts?access_token=XXX&limit=5&callback=?";
var url3 = "https://graph.facebook.com/Footengo69/posts?access_token=XXX&limit=5&callback=?";
$.getJSON(url,function(json1){
$.getJSON(url2,function(json2){
$.getJSON(url3,function(json3){
var json = {};
json['json1'] = json1;
json['json2'] = json2;
json['json3'] = json3;
var json_array = [];
json_array.push(json);
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
var html = "<ul>";
//loop through and within data array's retrieve the message variable.
$.each(json.json1.data, function(i,fb){
if (typeof fb.picture != "undefined") {
html += "<li>" + fb.message + "</br>" + '<img SRC="' + fb.picture + '">' + "</br>" + fb.created_time + "</li></br>";
}
else{
html += "<li>" + fb.message + "</br>" + fb.created_time + "</li></br>";
}
});
$.each(json.json2.data,function(i,fb){
if (typeof fb.picture != "undefined") {
html += "<li>" + fb.message + "</br>" + '<img SRC="' + fb.picture + '">' + "</br>" + fb.created_time + "</li></br>";
}
else{
html += "<li>" + fb.message + "</br>" + fb.created_time + "</li></br>";
}
});
$.each(json.json3.data,function(i,fb){
if (typeof fb.picture != "undefined") {
html += "<li>" + fb.message + "</br>" + '<img SRC="' + fb.picture + '">' + "</br>" + fb.created_time + "</li></br>";
}
else{
html += "<li>" + fb.message + "</br>" + fb.created_time + "</li></br>";
}
});
html += "</ul>";
//A little animation once fetched
$('.facebookfeed').animate({opacity:0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity:1}, 500);
});
});
});
};
</script>
</head>
<body onload="fbFetch();">
<div class="facebookfeed">Loading...</div>
</body>
I have 5 last posts for my 3 account, but 5 lasts from the first page, 5 last posts from the second one ... That give me this result:
You can do this with one request instead of three:
returns
The complete logic would be
See the working fiddle at http://jsfiddle.net/6fhq3dat/2/ (exchange the access token first)...