Adding a (more advanced) Facebook news feed to a website

A while back I wanted to add a custom Facebook feed to a website in order to display posts from a client’s Facebook page.  The website was beautifully designed and I didn’t want to ruin the aesthetic by plonking a Facebook branded iframed news feed into it that looks like this.

So I struggled through the Facebook Developers website and after a few weeks of turmoil I was able to put together a PHP script which interacts with the Facebook API and extracts the feed data to allow you to display it however you want!  Here’s a Demo.

To view the basic PHP code behind the plugin then check out the original tutorial here. Or if you want to add photosvideosevents, be able to filter out certain post types and display likesshares and comments then check out the Custom Facebook Feed plugin.

You can download the plugin over at Smash Balloon, and watch a video below of how to setup and customize it.

80 much appreciated responses...

  1. Mark says:

    Thanks for this! How do you adjust it so that only the person’s status updates are shown and not other people posting on the page?

    • johndoesdesign says:

      To stop comments showing up just replace ‘feed?’ in your URL with ‘posts?’. This should just show the posts from the author.

  2. Danielle says:

    I’m trying my best to get this to work. My link works. I can echo it out and paste the link into the address bar and view the information. Beyond that, everything comes out blank. Is there an extra step I should be doing? What could be a possible reason for the data not coming out the way it should?

    • johndoesdesign says:

      If you can view the JSON feed then you should be able to pull that information using the PHP. If you can’t then my first simple but important question is are you using this on a server (either remote or local) which has PHP installed?

  3. freddie says:

    ok so tried this new code as you said to on the http://johndoesdesign.com/blog/2011/php/adding-a-facebook-news-status-feed-to-a-website/ page and still getting a blank white page except now i have the like div with the thumb and page Title with the like button other then that its a blank white page not sure what im doing wrong if any thing

    • johndoesdesign says:

      Are you able to view the JSON feed at your link? (https://graph.facebook.com/PAGE_ID/feed?access_token=ACCESS_TOKEN) If not, then it’s likely that the page/group/profile you’re trying to pull isn’t public and so you can’t access the feed via the graph. If you can see the feed but you’re not able to pull it using the PHP then my first question would be whether PHP is installed/enabled on your server?

  4. Gaël says:

    Do you know how I can get the JSON feed in french instead of english (i.e: “Posted on their own link”).

    I checked in the code, but it seems to be defined by the JSON feed. Could you help me on this topic ?

  5. Joe says:

    I’ve just spent a day doing something similar with Twitter and their API. Their documentation is terrible!

    This is perfect for what I need for the Facebook part of my news feed and is going to save me a tonne of time!

    Thanks for the great article and great site!

    • johndoesdesign says:

      No problem Joe. Cheers!

  6. freddie says:

    i can see the json feed and php is installed and working when using the phpinfo(); it displays the php information my graph link is

    https://graph.facebook.com/238799632921950/feed?access_token=126910474151671|oa9TChRco3kJHss6f9tSFDNbppI

    $FBid = ‘238799632921950’;

    https://graph.facebook.com/‘ . $FBid . ‘/feed?access_token=126910474151671|oa9TChRco3kJHss6f9tSFDNbppI’);

  7. freddie says:

    http://pastebin.com/H9i3E1Ae went ahead and also pasted the entire doc here

  8. victoria says:

    The feed is working for me but pictures aren’t showing up. Any idea why not?

    Thanks

    • James says:

      I’m having the same problem, it’s a hard one to search for. Using ‘posts’ returns everything except single photos. I get the multiple photo posts and regular status updates. Using the Graph Explorer they all show up, but running from my site they do not. I can only guess it’s a permission issue, but I’ve tried for a few days now with no luck.

      Anyone with insight on this? You’ll be my hero!

  9. Hello John.

    Firstly an excellent article and tutorial. I have the feed displaying on my site. (I have used part 2 of the tutorial, the advanced one).

    I have also used your ‘News Feed Example’ – (http://johndoesdesign.com/facebook-news-feed-example.php)

    My feed shows up the ‘likes’ that the Facebook Client has made and your feed doesn’t. I wish for mine not too. Is there a way to remove ‘likes’?

    Thanks

    • oh … and also I don’t want to show their comments ;)

      Thanks in advance.

    • Hello,

      I was looking into having only the posts without comments from users. It’s it simple:

      The /posts api returns the posts created by the user (on her own wall or the wall of a friend), and it may include any kind of content such as shared links, checkins, photos and status updates.

      The /feed includes all the things that a user might see on his own wall; again shared links, checkins, photos and status updates. This also includes posts made by friends on the user’s wall.

      The /statuses api returns only status updates posted by the user on his own wall.

      The /home api returns a stream of all the posts created by you and your friends, i.e. what you usually find on the “News Feed” of Facebook. (You didn’t ask for this one, but I include it for completeness.)

      Cut and paste from another post

      • johndoesdesign says:

        Thanks for posting this Henrik, very useful! Reece, to stop comments showing up just replace ‘feed?’ in your URL with ‘posts?’.

        • Thank you John and Henrik, works great! Unfortunately the interesting stuff my client does it mainly comments on others images so I will need the full feed. I really just wanted to remove all the likes statuses.

          Thank again

  10. Hi John,

    Thanx for sharing this informatie. I have the feed displaying on my site: http://www.btgroep.nl/test.php (part 2 of the tutirial).

    My question: it shows thumbnailversions of the picture used on Facebook. The original once are much larger then shown here in the feed. Is there a way (maybe another variable) to get the original images into the feed?

    Thanx in advance. Cheers,
    Casimir

  11. Hello John,

    I’m really happy i found your article and it helps me a lot.
    As Reece writes, the user comments comes up as well. Would there be a way to only have the posts from the site without the comments?

    Thanks

    • John B says:

      Hey Henrik, glad you like it! Yep you can display just the posts and not the comments.. Check out the demo I put together here, and you can download the code here.

  12. Ellman says:

    Thank you for this tutorial, I have a question that few people seem to be asking:
    Is it possible to have the FULL facebook newsfeed functionality exported to a website?

    This one come close, but users cannot view or leave a comment on the posts even if they are logged in, is it even possible to add the comment functionality on an external page?

    I know it’s possible to make it so that the comments already posted are viewed, but I have yet to see wether it’s possible to leave comments.

  13. freddie says:

    so am i doing somthing wrong or have i missed somthing or what cause all im getting is a white page with the like button my page http://freddieyoho.com/webdesigns/newsfeed2/newsfeed.php

    php doc here http://pastebin.com/H9i3E1Ae

    • John B says:

      Try putting your Page ID and Access Token into the demo page here to see whether it works.

  14. Hello John,

    I was wondering whether there is any way to speed up the load time of the feed? Is this an issue you have come across?

  15. Jimmy Williams says:

    Thanks for the examples. I added some javascript on the page to deal with the posts with missing img tags.
    Looks like the /n newlines are not passing through to the output. Any ideas on getting a to show in the message section?

    http://jacksoncountyso.com/facebookfeed.php

    Still tinkering.

  16. Kyle says:

    Great work!

    The only thing I need help with is to display comments. At present I can see how many comments have been made but is it possible to show these comments?

    Thanks.

  17. freddie says:

    so i finally figured out why i couldnt get it to load on my site apparently i had this in my error log

    20130314T211814: /newsfeed2/newsfeed.php
    PHP Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0

    changed the following setting in my php.ini was a value of Off i set to On and seems to be working great, thanks for this

    ; Fopen wrappers ;
    ;;;;;;;;;;;;;;;;;;

    ; Whether to allow the treatment of URLs (like http:// or ftp://) as files.
    ; http://php.net/allow-url-fopen
    allow_url_fopen = On

  18. Simon says:

    Hey there!

    Thanks for your great work on this script!

    I ‘m having issues of elements appearing in the newsfeed extremely huge and therefore not fitting very well into the website…
    I am not a PHP programmer, so I could not find any condition in your code of resizing the preview pictures of a video for example which is shown in its native size…

    Keep up the great work, I’m sure you saved a lot of guys out there (me too!) a lot of hours and headache! :-)

    • John B says:

      Hey Simon, glad I could help and happy that I’ve been able to save you and other people some time! Resizing the images can just be done with some CSS. Set the images to be max-width: 100%; and make sure that the container that holds the feed has a width set on it. If you need any more help then feel free to use this form to email me! http://wordpress-wings.com/custom-facebook-feed/support/

  19. Susan says:

    I need more clarity on this as I find the page admins comments to users who post comments on the page owner’s wall weird, out of context. They remain regardless of whether I use feed or posts. I know it’s coming from this line as I gave it a color of red. What is the statuses api, as opposed to the feed or posts api.

    Henrik: “The /posts api returns the posts created by the user (on her own wall or the wall of a friend), and it may include any kind of content such as shared links, checkins, photos and status updates.

    The /feed includes all the things that a user might see on his own wall; again shared links, checkins, photos and status updates. This also includes posts made by friends on the user’s wall.

    The /statuses api returns only status updates posted by the user on his own wall.”

  20. Susan says:

    Found this on Stack OverFlow. The last comment works. I added it below this line.

    //Explode News and Page ID’s into 2 values
    $StatusID = explode(“_”, $news->id);
    //Removes extraneous out of context stuff like comments to others from page admin
    if (empty($news->message)) { continue; }

    http://stackoverflow.com/questions/13147858/facebook-graph-only-include-status-messages-posted-by-page

  21. Susan says:

    I also changed the likes, comments, shares into a horizontal list, with less spacing between lines.

    //Check for likes/comments/share counts
    echo ‘Likes: ‘;

    if (empty($news->likes->count)) { echo ‘0’; }
    else { echo $news->likes->count; }

    echo ‘Comments: ‘;

    if (empty($news->comments->count)) { echo ‘0’; }
    else { echo $news->comments->count; }

    echo ‘Shares: ‘;

    if (empty($news->shares->count)) { echo ‘0’; }
    else { echo $news->shares->count ; }

    echo ”;

  22. Susan says:

    Oops my inline list style was stripped out and the pre tag does not work. Trying again.

    //Check for likes/comments/share counts
    echo ‘<ul class=”meta” style=”list-style-type: none;margin:top:-10px;”><li style=”display: inline;padding: .2em .2em;”>Likes: ‘;

    if (empty($news->likes->count)) { echo ‘0’; }
    else { echo $news->likes->count; }

    echo ‘</li><li style=”display: inline;padding: .2em .2em;”>Comments: ‘;

    if (empty($news->comments->count)) { echo ‘0’; }
    else { echo $news->comments->count; }

    echo ‘</li><li style=”display: inline;padding: .2em .2em;”>Shares: ‘;

    if (empty($news->shares->count)) { echo ‘0’; }
    else { echo $news->shares->count ; }

    echo ‘</li></ul>';

  23. deepak says:

    Hi,
    It is not fetching all contents from news feed like pictures, videos shared on my wall by my friends, Posts in which i am tagged. How to do that?

  24. Lianne says:

    Fantastic post, a huge help. I have three points/questions to address.

    First, Even though I have changed the URL to be “posts?”, is there a way to only display posts from the wall? I have some from the client responding to guest posts.
    (http://www.greenbanktrio.ca/news.php)

    Second, Is there a way to explode the paragraphs so that they aren’t lumps of text? (I’m still new to php, learning very slowly!)

    Third, and this is just because I am a designer, is there a way to display the date it was posted as the date? (Ie May 20th). I know it is possible using http://php.net/manual/en/function.date.php, I am just unsure how to go about implementing it into the php above.

    And lastly (bonus) I am unsure why images and videos are not showing up. Still looking into it though.

    Fantastic work, thanks John! I’ll be tweeting this one!

    • Lianne says:

      ok it’s down for the time being, still trying to figure something out. It is now located at:

      http://greenbanktrio.ca/news_test.php

      • Shawn says:

        I was wondering if you ever figured out how to change the date format?

      • Shawn says:
    • Frank says:

      Dear Liane,
      I am trying to figure out, how to put the facebook news feeds into a website (wordpress) , like you did on the grenbanktrio website.

      Each news item in one box looks pretty nice.

      I have the php script up and running on my webspace. But I do not know, how to automate my site, so that the facebook news are coming on startpage box by box.

      Hopefully find a solution.
      Kind regards from Germany

  25. Jeremy says:

    Is it possible to access the bigger picture sizes? Mostly, you get the “q” pictures, I’d like to display the “b” pictures. Is this somehow possible?

    • John B says:

      Sure is. Check out the demo I put together here and you can download the code here.

  26. Jeremy says:

    The “date issue” is easy: date(“d-m-Y”, strtotime($news->created_time)) or whatever you wish

  27. Shawn says:

    Hey, I figured out how to change the date/time format.

    //create a function
    function formatdate( $s )
    {
    return date( “d-m-Y”, strtotime( $s ) );
    }

    //echo
    echo formatdate( $news->created_time );

  28. Susan says:

    Liaanne see this, that I posted above.

    Found this on Stack OverFlow. The last comment works. I added it below this line.

    //Explode News and Page ID’s into 2 values
    $StatusID = explode(“_”, $news->id);
    //Removes extraneous out of context stuff like comments to others from page admin
    if (empty($news->message)) { continue; }

    http://stackoverflow.com/questions/13147858/facebook-graph-only-include-status-messages-posted-by-page

    simply add this line

    if (empty($news->message)) { continue; }

    below this one

    $StatusID = explode(“_”, $news->id);

  29. Susan says:

    Jeremy sand Shawn thanks. However i apparently need more clarity as I currently have Posted 0

    I tried

    echo ' Posted '. date(“d-m-Y”, strtotime($news->created_time)) . '';

    and

    echo ' Posted '. formatdate( $news->created_time ). '';

    Does anything need to be modified in the original date function? I tried implements Shawn’s function in multiple places with no luck.

  30. Hi,

    Is there a way to limit the length of each post?

    Thanks in advance,
    Yanick

  31. Rohin says:

    Hello John,
    Liked your article so much.
    It’s almost close to something I was trying to build.
    I think that can also be made just by editing the code line:

    $FBpage = file_get_contents(‘https://graph.facebook.com/’ . $FBid . ‘/feed?access_token=YOUR_ACCESS_TOKEN&limit=10′);

    Here I think you are showing feed of a Facebook page.
    But what I want is:
    to show a friend’s activities like we see in our home page at Facebook website.

    or we can like in the “News Feed page” of Facebook(the user’s home page), where he/she see activities of friends and other related things.

    Can that be done? with some editing in your code?

    I hope it’s possible… ?
    looking forward to your reply..
    Thanks,
    Rohin

    • John B says:

      Hey Rohin. I don’t believe this is possible unfortunately due to Facebook’s privacy policy. You can’t display a news feed of friends if those friends’ feeds aren’t publicly accessible. Otherwise I could pull in the posts of all of your friends even though I’m not friends with them. Hope that makes sense.

  32. Hey, thanks a lot for this tutorial, but I have quite a problem.

    I’ve put your code on my index.php page, I’ve put the access token right but I get these errors :

    I don’t know what to do to get it right.

  33. Oops had a little problem lol.

    Warning: file_get_contents(http://graph.facebook.com/headbanger.clothing/feed?access_token=XXXXXXXXXXXXXXXXXXXXXXX&limit=10) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\wamp\www\headbangerco\index.php on line 36
    Facebook News Feed

    Notice: Trying to get property of non-object in C:\wamp\www\headbangerco\index.php on line 76

    Warning: Invalid argument supplied for foreach() in C:\wamp\www\headbangerco\index.php on line 76

    Here is my code.

  34. Meant “here is my error”, damn it’s early and it’s Monday. -_-

  35. Nevermind, was a problem with the php.ini file I had on wamp, solved!

    • John B says:

      Awesome, glad you got it figured out!

  36. cheewen says:

    if I using this php code on close group ,why doesn’t work? How can solve this problem?

    • John B says:

      Hey. This only works for public groups or pages. This is to do with Facebook’s privacy policies. You can’t just grab a non-public feed and display it to the world. To test whether your page or group will work with the script then try it out on this demo I put together.

  37. Thiago Melo says:

    Thanks for the great post
    Is there a way to sort by most liked?

    • John B says:

      I haven’t built that in yet but plan to make it a feature in the WordPress plugin that I’m releasing next month. If you put your email in here then I’ll notify you of when it’s available to download.

  38. stephen hill says:

    hi, I have the same question to ask that other people on this blog have, I need to pull the B images in but all mine are coming in as s

    What do I need to add to the code to do this, been looking for ages and cant figure it out

    thanks so much

    • Jason Brown says:

      Find the line that says…

      else if ($news->type == ‘photo’) {

      and add this immediately below it…

      $news->picture = str_replace(‘_s’, ‘_b’, $news->picture);

  39. Charles says:

    Works great! Thanks for posting!

    • John B says:

      Awesome, glad to hear it!

  40. Jason Brown says:

    Just a quick post to say thank you to Johndoesdesign!!!!! This code is awesome!!!!!

    Quick question – is there any way to get the name of the user that posted each of the posts? I assumed $news->name would work but nothing is being displayed…

    • John B says:

      No probs mate, glad you found it helpful! I have a new version out over at WordPress Wings if you’re interested.

      To grab the name you should be able to do $news->from->name. Give it a try and let me know whether it works for you.

      • Jason Brown says:

        That worked perfectly, John – thank you!

        The new plugin looks very cool. Unfortunately I don’t use WordPress so it’s of limited use to me. I would, however, be happy to send you some beer tokens as a sign of my appreciation for your hard work. Have you thought about adding a ‘Donate’ option to your site?

  41. Nick says:

    Thank you — very useful indeed!

    I wish Facebook would offer an XML feed, too. If you know XSLT, it’s much simpler to transform XML than it is to process JSON.

    • John B says:

      Haha yep tell me about it. Glad you found the script useful mate!

  42. Jack says:

    I can’t get this to work on my website but if I test it in your demo it works just fine… what am I missing or doing wrong? Any help?

    • John B says:

      Hey Jack, are you running the script on a PHP enabled server? I’ve recently improved the code and have it available as a standalone download over at http://wordpress-wings.com if you want to check it out.

  43. Tony says:

    Hello,
    I just went through the instructions and allowed my settings so I can see the posts after pasting the url address (https://graph.facebook.com/myID/posts?access_token=myAccesToken). Don’t know why, but if I change ‘posts’ to ‘feed’ (in the url) it shows me no data..

    {
    “data”: [

    ]
    }

    but it’s not the problem for which I’m looking for a solution.

    The problem is that when I put it into a abc.php file (just pasted your source, filled the pageID and access_token and added a to the end), I can’t see any content in a page even in a html source :/ Must there be some special allowing of JSON ext of PHP anywhere there on the server? Any other .php files are working well and without a problems, but this with json is not working properly :/

    Don’t you know the potential cause of this problem, please? ;)
    Thanks in advance :)

    • John B says:

      Hey Tony, you might want to check that JSON is enabled on your server, as you won’t be able to retrieve the JSON data without it.

      You could run a simple test in your PHP file like so:
      if ( function_exists(‘json_decode’) ) echo ‘JSON is on!';

      • Tony says:

        Hey John B,
        the test you’ve recommended returned the desired string. So the JSON is ON on my server. The second post I’ve posted here (“Your code returns me..”) was the case of I tried to run the script on another server (where the JSON – due to the result of the test – is ON as well) :/ :(
        Thanks for helping me ;)

      • Tony says:

        Hey John B,
        my answer posts somehow dissapeared from here..

        The JSON is ON on the server.

  44. Tony says:

    Your code returns me

    Notice: Trying to get property of non-object in /export/home/xsrna2/public_html/fb.php on line 40

    Warning: Invalid argument supplied for foreach() in /export/home/xsrna2/public_html/fb.php on line 40

    which is
    40 foreach ($fbdata->data as &$post)
    41 {
    42 $posts .= ”;

    Don’t you know how to manage it? ;) Thx

    • John B says:

      Hey Tony, that likely means that file_get_contents can’t retrieve the feed as allow_url_fopen isn’t enabled in your PHP settings. See the comment here for a solution: http://johndoesdesign.com/blog/2011/php/adding-a-facebook-news-status-feed-to-a-website/#li-comment-80643

      • Tony says:

        Hey John B,
        I tried to edit the code
        (so it looks like

        $page_id = ‘myId';
        $access_token = ‘myAT';
        //Get the JSON

        $url = ‘https://graph.facebook.com/’ . $page_id . ‘/posts?access_token=’ . $access_token;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $json_object = curl_exec($ch);
        curl_close($ch);

        //Interpret data
        $fbdata = json_decode($json_object);

        foreach ($fbdata->data as &$post )
        {
        $posts .= ”;
        $picture = $post->picture;
        if ( !empty($picture) ) $posts .= ”;
        $posts .= ‘link . ‘”>’ . $post->story . ‘‘;
        $posts .= ‘link . ‘”>’ . $post->message . ‘‘;
        $posts .= ” . $post->description . ”;
        $posts .= ‘‘;
        };
        ) but it still returns:
        Warning: Invalid argument supplied for foreach() in /export/home/xsrna2/public_html/fb.php on line 49 (that’s the line with
        foreach ($fbdata->data as &$post )
        ). Sorry for bothering you :/

        I pasted your hint cURL code over $json_object = @file_get_contents(‘https://graph.facebook.com/’ . $page_id .
        ‘/posts?access_token=’ . $access_token); (cause I read when there’s this kind of mistake, allow_url_fopen isn’t enabled so the file_get_contents won’t work), is it right?

        Thanks for your patience ;)

Feel free to add your comment..

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>