Reputation:
I have just began to start dabbling in JSON and Facebook's Graph API. With the following I've been able to pull posts from my Facebook page:
$page_id = '???';
$access_token = '???';
$json_object = @file_get_contents('https://graph.facebook.com/' . $page_id .
'/posts?access_token=' . $access_token . '&limit=100');
$fbdata = json_decode($json_object);
foreach ($fbdata->data as $post ) {
$posts .= '<p><a href="' . $post->link . '">' . $post->story . '</a></p>';
$posts .= '<p><a href="' . $post->link . '">' . $post->message . '</a></p>';
$posts .= '<p>' . $post->description . '</p>';
$posts .= '<br />';
}
echo $posts;
However Facebook doesn't allow any more than 100 posts in one JSON request. Is there a way around this by making multiple requests or should I be going about this in a different way entirely?
Does anybody know how I could display all existing posts from my Facebook page?
Upvotes: 0
Views: 118
Reputation:
An infinite amount of posts can be displayed by paginating them like so:
//Set page variable/page number
if($_GET['page'] == 0) {
$page = 1;
}
else {
$page = $_GET['page'];
}
//Page increments/decrements
$next_page = intval($page + 1);
$prev_page = intval($page - 1);
//Set offset if it isn't the first page
if ($page > 1) {
$offset = $page * 5 - 5;
}
//Facebook Dev details
$page_id = '???';
$access_token = '???';
//Get JSON for specified page
$json_object = @file_get_contents('https://graph.facebook.com/' . $page_id .
'/posts?access_token=' . $access_token . '&limit=5' . '&offset=' . $offset);
//Interpret the data
$fb_data = json_decode($json_object);
foreach ($fb_data->data as $post ) {
$posts .= '<p><a href="http://facebook.com/' . $post->id . '">' . $post->story . '</a></p>';
$posts .= '<p><a href="http://facebook.com/' . $post->id . '">' . $post->message . '</a></p>';
$posts .= '<p>' . $post->description . '</p>';
$posts .= '<br />';
}
//Display posts
echo $posts;
//If page isn't the first page add previous button
if ($page > 1) {
echo '<a href="?page=' . $prev_page . '">' . 'Previous' . '</a>';
}
//Total offset of posts on next page
$next_page_offset = $offset + 5;
//Make next page object
$json_next_page_object = @file_get_contents('https://graph.facebook.com/' . $page_id .
'/posts?access_token=' . $access_token . '&limit=5' . '&offset=' . $next_page_offset);
//Get JSON for next page
$fb_next_data = json_decode($json_next_page_object);
//Echo next button if size of next data is greater than one
if( sizeof( $fb_next_data->data) > 0 ) {
echo '<a href="?page=' . $next_page . '">' . 'Next' . '</a>';
}
Probably needs some improvement, but it works as desired so far.
I hope what I've got so far can help others in making a basic and easy to manage Facebook feed :]
Upvotes: 1