Get the Latest Post of a Facebook Page

27 Jan 2013

My awesome friend Lewis King wanted to display the latest facebook post in the footer of a site that he's building. He's not a developer, and facebook didn't make it easy.

The tangled web of facebook developer documentation and inadequate access token description. Most blog tutorials out there are outdated because of the introduction of required access tokens.

My solution:

  1. Get yourself an access token (remember that you need to be an admin of the page that you want to read from). You will need to select "manage_pages" from the extended permissions section before authorising the token.
  2. Find your USER_ID by going to http://graph.facebook.com/USERNAME
  3. We have one access token, but we need to get a long-life access token for your page. You can get this and token for your apps at this URL: https://graph.facebook.com/USERID/accounts?accesstoken=ACCESS_TOKEN
  4. Take this new access token and go to: https://graph.facebook.com/PAGEID/promotableposts?accesstoken=LONGLIFEACCESSTOKEN
  5. You will now see an object with the page's latest posts with various fields available including the message and information about any URLs that were posts e.g. image and description.
  6. That was the difficult bit done. It's very simple from a code point of view to get the page post data and show the latest one and link to it.

    <?php 
      $data = get_data("https://graph.facebook.com/PAGE_ID/promotable_posts?access_token=ACCESS_TOKEN");
      $result = json_decode($data);
    ?>
    

    get_data is a wrapper function for curl.

    With this information we can take the first item in the data array and get the message. Obviously this code should probably have more validation in it than it does.

    <?php        
      $latest_post =  $result->data[0];
      $latest_post_text = $latest_post->message;
      $latest_post_link = $latest_post->actions[0]->link;
    ?>
    <a href="<?php echo $latest_post_link ?>"><?php echo $latest_post_text ?></a>
    

    There you go, Lewis.