Skip to content

Instantly share code, notes, and snippets.

@jasdeepkhalsa
Last active December 15, 2015 19:09
Show Gist options
  • Save jasdeepkhalsa/5309286 to your computer and use it in GitHub Desktop.
Save jasdeepkhalsa/5309286 to your computer and use it in GitHub Desktop.
Get back the latest post from a Facebook page by Jasdeep Khalsa
<div id="fb-text">Like us on Facebook for the very latest updates, exclusives, offers and competitions!</div>
/**
* Facebook Latest Post
* Get back the latest post from the Facebook page (which is public Facebook Graph data),
* otherwise if the service cannot be accessed, throw a console error and fallback to some default text
* @requires jQuery 1.8.2+
* @author Jasdeep Khalsa
*/
var fb_div = '#fb-text';
var fb_default_text = 'Like us on Facebook for the very latest updates, exclusives, offers and competitions!';
var timeout = 5000;
var weekday = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
function fbErrorCallback(){
$(fb_div).html(fb_default_text);
console.error('Facebook service failed');
}
var fb_page_username = 'sample';
var fb_error_callback = setTimeout( fbErrorCallback, timeout ); // Start the error timer
var fb_json_url = 'http://www.example.com/api/facebook-json.php'; // URL to facebook-json.php file
var fb_jqxhr = $.getJSON(fb_json_url)
.success(function(data) {
clearTimeout(fb_error_callback);
for(var id in data.data){
var fb_post = data.data[id];
if(fb_post.from.name == fb_page_username){
// Only get back posts relating to your company NOT customers' posts
if(fb_post.message != undefined || ''){
var text = fb_post.message || fb_default_text;
var date = new Date(fb_post.created_time);
if(date != 'Invalid Date' || undefined || ''){
var minutes = (date.getMinutes()<10?'0':'') + date.getMinutes(); // Make sure minutes show properly when < 10
var day = weekday[date.getDay()];
var html = '<i>'+day+' '+date.getHours()+':'+minutes+'</i>'+' - '+text+'<br/>';
$(fb_div).html(html); // Update the element
return; // Exit the loop
} else{
var html = text;
$(fb_div).html(html); // Update the element
return; // Exit the loop
}
}
}
}
})
.error(function() { fbErrorCallback(); });
<?php
// Output a Facebook Page's Latest Post in JSON using PHP
// If the App secret for the App ID is reset then a new App Token will have to be produced
// Otherwise this App Token has no expiry date
// The App Token/Access Token can be found at: https://developers.facebook.com/tools/access_token
$fb_access_token = 'App|Token'; // This is the App Token, which has no expiry date
$fb_username = 'username';
$fb_graph_url = "https://graph.facebook.com/{$fb_username}/posts?access_token={$fb_access_token}&fields=from,message,created_time"; // Choose which fields to bring down, remove parameter to receive all fields
$fb_page_posts = file_get_contents($fb_graph_url);
header('Content-type: application/json');
echo $fb_page_posts;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment