Website Facebook feed

A twitter friend asked me about creating a custom feed for a Facebook wall. Pretty easy with the php sdk, but when I looked at the source it turns out I made it another way. Better or worse? You tell me.

The dirty secret

PHP’s file_get_contents. Here goes.

$content = file_get_contents('https://graph.facebook.com/galleriaduvan/posts?access_token=ACCESS_TOKEN');

You need an access token for this, get one like this (small warning, it may expire). Create a Facebook app and add the client_id and client_secret like below.

https://graph.facebook.com/oauth/access_token?client_id=6410********7221&client_secret=b4a761c0a6************9692ffd58&grant_type=client_credentials

This will return the access token needed to get the content of the Facebook page.

Now your variable $content (from above) will contain a JSON-feed.

Decode it with

$content = json_decode($content, true);

Then run a foreach to output the array (see below for code explanation).

<?php foreach ( $content['data'] as $fb ) : ?>
  <?php if ( $fb['message'] ) : ?>
    <div>
     <?php echo wpautop($fb['message']) ?>
     <?php $replace = array('_s.jpg', '_s.png') ?>
     <?php if ( $fb['picture'] ) : ?>
      <p><img src="<?php echo str_replace($replace, '_n.jpg', $fb['picture']) ?>" /></p>
     <?php endif ?>
     <time datetime="<?php echo $fb['updated_time'] ?>"><?php echo nicetime($fb['updated_time']) ?></time>
    </div>
  <?php endif ?>
<?php endforeach ?>

Line 2: If there is Facebook wall posts (called messages in the JSON) then on line 4 output the message with the WordPress wpautop-function

If there is a image (line 6) then print the image but replace the small feed image with a bigger one (from _s (small) to _n (normal).

On line 9 output the updated time with a custom time ago-function. Tho you could use WordPress built in function for this: human_diff_time

Download source/example-file

Comments are closed.