How To Display Facebook Page Posts On Website Using PHP?

Before we start coding, you might be someone NOT interested in coding. If that's the case, you should use a website plugin like SociableKIT. Watch the following video.

What's next? You can try SociableKIT now, view a live demo here or continue with the code tutorial below.

Let's code!

Hey guys! We have a new Facebook script for you!

This one is closely related to our previous FB scripts: Displaying Facebook page photos and events on your website.

For those who are not familiar with it, our Facebook scripts can synchronize data, like photo albums and events, from your Facebook page to your website.

Now it's time to share with you how to do it with your Facebook page posts! Today we will display Facebook page posts on your PHP wesbite.

I know, you can embed your Facebook page posts using the Facebook page plugin, but you cannot customize the look and feel. It looks like the default Facebook interface.

Don't get me wrong, it looks good! But sometimes, our design scheme or our clients have a different requirement, they want the Facebook feed to look different.

The good news is, our code for today is a way to do it!

Today's post will cover the following content:

1.0 Source Code Overview
2.0 Display Facebook Page Posts Feed on Website - Output
3.0 Get your page access token
4.0 Create index.php and add a page title.
5.0 Enable Bootstrap
6.0 Initialize Variables
7.0 Get JSON Contents
8.0 Decode JSON
9.0 Loop Through Posts
10.0 Format Time
11.0 Show Post Details
12.0 Link To Content
13.0 Custom CSS
14.0 How to Display Likes and Comments?
15.0 What People Say About This Code?
16.0 Download Source Code
17.0 What’s Next?
18.0 Related Source Codes
19.0 Some Notes

Let’s get started!

1.0 Source Code Overview

Today we’re going to do a code that:

1. Gets any type of posts like videos, statuses or pictures, from a Facebook fan page wall feed (using Facebook Graph API).

2. Display these posts or contents to a webpage (assuming it is your website) beautifully with Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step by step Bootstrap tutorial here. It is also responsive so it’s one advantage for mobile devices.

2.0 Facebook Page Posts Feed - Output

2.1 BASIC Source Code Output

It is important to know where we are going. You can view output of our step by step tutorial here:

display Facebook page posts on website - demo screenshot

2.2 PRO Source Code Output

display-fb-timeline-feed-PRO-demo-screenshot

PRO source code also has a timeline view.
site-timeline-view-display-facebook-page-timeline-feed-on-website

Now, let's take a look at how the BASIC source code was made. Enjoy the following step by step tutorial!

3.0 Get your page access token

Before you can get any data from your Facebook page via the graph API, you need a "page" access token.

Follow this detailed tutorial about how to get a page access token: How to get a Facebook page access token?

Replace YOUR_ACCESS_TOKEN with your page access token.

4.0 Create index.php and add a page title.

<?php
$page_title = "Facebook page posts";
?>

5.0 Enable Bootstrap

Put a Bootstrap-enabled basic HTML after the code on section 3.0

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title><?php echo $page_title; ?></title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

</head>
<body>

<div class="container">
	<div class='col-lg-12'>

	<!-- page feed code will be here -->

	</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->

</body>
</html>

6.0 Initialize Variables

Inside the div tag with 'container' class, put the page header and initialize the essential variables.

<?php
echo "<h1 class='page-header'>{$page_title}</h1>";

$fb_page_id = "change_to_your_fb_page_id";
$profile_photo_src = "https://graph.facebook.com/{$fb_page_id}/picture?type=square";
$access_token = "YOUR_ACCESS_TOKEN";
$fields = "id,message,picture,link,name,description,type,icon,created_time,from,object_id";
$limit = 5;
?>

7.0 Get JSON Contents

Specify the following JSON url and get contents.

$json_link = "https://graph.facebook.com/{$fb_page_id}/feed?access_token={$access_token}&fields={$fields}&limit={$limit}";
$json = file_get_contents($json_link);

8.0 Decode JSON

Decode the JSON string and count the given items.

$obj = json_decode($json, true);
$feed_item_count = count($obj['data']);

9.0 Loop Through Posts

Loop through the given items and prepare the values on variables.

for($x=0; $x<$feed_item_count; $x++){

	// to get the post id
	$id = $obj['data'][$x]['id'];
	$post_id_arr = explode('_', $id);
	$post_id = $post_id_arr[1];

	// user's custom message
	$message = $obj['data'][$x]['message'];

	// picture from the link
	$picture = $obj['data'][$x]['picture'];
	$picture_url_arr = explode('&url=', $picture);
	$picture_url = urldecode($picture_url_arr[1]);

	// link posted
	$link = $obj['data'][$x]['link'];

	// name or title of the link posted
	$name = $obj['data'][$x]['name'];

	$description = $obj['data'][$x]['description'];
	$type = $obj['data'][$x]['type'];

	// when it was posted
	$created_time = $obj['data'][$x]['created_time'];
	$converted_date_time = date( 'Y-m-d H:i:s', strtotime($created_time));
	$ago_value = time_elapsed_string($converted_date_time);

	// from
	$page_name = $obj['data'][$x]['from']['name'];

	// useful for photo
	$object_id = $obj['data'][$x]['object_id'];
}

10.0 Format Time

To get "time ago" text, put the following function code below the ending HTML tag.

// to get 'time ago' text
function time_elapsed_string($datetime, $full = false) {

	$now = new DateTime;
	$ago = new DateTime($datetime);
	$diff = $now->diff($ago);

	$diff->w = floor($diff->d / 7);
	$diff->d -= $diff->w * 7;

	$string = array(
		'y' => 'year',
		'm' => 'month',
		'w' => 'week',
		'd' => 'day',
		'h' => 'hour',
		'i' => 'minute',
		's' => 'second',
	);
	foreach ($string as $k => &$v) {
		if ($diff->$k) {
			$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
		} else {
			unset($string[$k]);
		}
	}

	if (!$full) $string = array_slice($string, 0, 1);
	return $string ? implode(', ', $string) . ' ago' : 'just now';
}

11.0 Show Post Details

Inside the for loop, show the profile image thumbnail, the type of what he shared and the caption entered by the user.

echo "<div class='row'>";

	echo "<div class='col-md-4'>";

		echo "<div class='profile-info'>";
			echo "<div class='profile-photo'>";
				echo "<img src='{$profile_photo_src}' />";
			echo "</div>";

			echo "<div class='profile-name'>";
				echo "<div>";
					echo "<a href='https://fb.com/{$fb_page_id}' target='_blank'>{$page_name}</a> ";
					echo "shared a ";
					if($type=="status"){
						$link="https://www.facebook.com/{$fb_page_id}/posts/{$post_id}";
					}
					echo "<a href='{$link}' target='_blank'>{$type}</a>";
				echo "</div>";
				echo "<div class='time-ago'>{$ago_value}</div>";
			echo "</div>";
		echo "</div>";

		echo "<div class='profile-message'>{$message}</div>";
	echo "</div>";
echo "</div>";
echo "<hr />";

12.0 Link To Content

Still inside the div with 'row' class on the previous step. Show the link to the actual content, the thumbnail and if it is a status, just show a link.

echo "<div class='col-md-8'>";
	echo "<a href='{$link}' target='_blank' class='post-link'>";

		echo "<div class='post-content'>";

			if($type=="status"){
				echo "<div class='post-status'>";
					echo "View on Facebook";
				echo "</div>";
			}

			else if($type=="photo"){
				echo "<img src='https://graph.facebook.com/{$object_id}/picture' />";
			}

			else{
				if($picture_url){
					echo "<div class='post-picture'>";
						echo "<img src='{$picture_url}' />";
					echo "</div>";
				}

				echo "<div class='post-info'>";
					echo "<div class='post-info-name'>{$name}</div>";
					echo "<div class='post-info-description'>{$description}</div>";
				echo "</div>";
			}

		echo "</div>";
	echo "</a>";
echo "</div>";

13.0 Custom CSS

Put some custom CSS inside the head tag, preferably under the CSS line of bootstrap.min.css

<style>
.profile-info{
	overflow:hidden;
}

.profile-photo{
	float:left;
}

.profile-photo img{
	width:40px; height:40px;
}

.profile-name{
	float:left; margin:0 0 0 .5em;
}

.time-ago{
	color:#999;
}

.profile-message{
	margin:1em 0;
}

.post-link{
	text-decoration:none;
}

.post-content{
	background: #f6f7f9; border: 1px solid #d3dae8; overflow:hidden;
}

.post-content img{
	width:100%;
}

.post-status{
	margin:.5em; font-weight:bold;
}

.post-picture{
	width:25%; float:left;
}

.post-info{
	width:70%; float:left; margin:.5em;
}

.post-info-name{
	font-weight:bold;
}

.post-info-description{
	color:#999;
}
</style>

14.0 How to Display Likes and Comments?

You just have to add the 'likes' and 'comments' on the $fields variable. It will show you additional data on the JSON result that you can parse and use in any way you want.

In the PRO demo, I added a feature that if the likes and comment count were clicked, it will show the actual likes and comments data. It was achieved using jQuery.

15.0 What People Say About This Code?

I'm so glad that other people are delighted by this code, here are some of them!

★★★★★ "This guy is the best. There was a small issue and he me helped right away. I recommend this script to everybody. Instead of wasting time by copy pasting, just purchased the package and saved a lot of time also it came with many ajax features." ~ Aykun

★★★★★ "BIG THANKS! I've been searching and messing around with SDK, Composer, FB APIs... to achieve to place feeds in my FB page to appear on my website without any luck until now." ~ Hip

★★★★★ "Hi there Mr. Ninja, thanks for that guide and your effort. It is working great, after I understood how to use it. :)" ~ Martin Pfeiffer

★★★★★ "Like a boss! You're awesome! Thanks a lot!" ~ Freddy Moran Jr.

★★★★★ "Thanks for the script!" ~ Omer Rosenbaum

★★★★★ "Thanks a lot. Amazing support. Let me know if there is anywhere that I can write a review." ~ A. Cetinkaya

16.0 Download Source Code

You can get the source code by following the whole, well detailed tutorial above. But isn't it more convenient if you can just download the complete source code we used, and play around it?

There's a small fee in getting the complete source code, it is small compared to the value or skill upgrade it can bring you, or income you can get from your website project or business.

For a limited time only, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE by clicking the green buy button below.

16.1 Download BASIC Source Code

FEATURES BASIC
Do it once: update your Facebook timeline feed and reflect it on your website Yes
Save time figuring out and coding these features on your website Yes
Display Facebook page name with link Yes
Automatically show type of post, it can be status, link, video, etc. Yes
Type of post is clickable, it links to actual content Yes
Status post will have "View On Facebook" link Yes
Link posts will show the link thumbnail, title, and description Yes
Shows posted photo Yes
Display number of likes Yes
Display number of comments Yes
Bootstrap UI enabled Yes
Responsive layout (great for mobile devices!) Yes
Show "time ago" of posts Yes
Show like and comment icons Yes
Free email support for 6 months. Yes
Free source code updates. Yes
Download Now

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

16.2 Download the PRO Source Code

FEATURES PRO
All features of the BASIC source code. Yes
Clickable link to other people or pages mentioned in a post Yes
Load people who liked and commented on a post via AJAX Yes
Show post comments Yes
Show people who commented and link to their profiles Yes
URLs on post will be a clickable link automatically Yes
Show some people who liked a post and link to their profiles Yes
Load more posts automatically when scrolling Yes
Will show newly loaded contents with all the features above Yes
Timeline view Yes
Responsive timeline view Yes
Uses a PHP Class (Object Oriented) Yes
4-Step Only Integration Yes
Include class & class instance Yes
printCSS_DsmFacebookTimeline(); method Yes
printContents_DsmFacebookTimeline(); method Yes
printJavaScript_DsmFacebookTimeline() method Yes
Well-documented via code comments Yes
Fast & friendly support from me for 9 months Yes
Download Now

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

Do you need more reasons to download the source code?

MORE REASONS TO GET IT
Buy only once, use on up to 10 websites and Facebook pages! Yes
No different kind of licenses. Yes
No many different pricing schemes. Yes
No monthly or any recurring fees. Yes
No need to rely on another website to render Facebook timeline feeds Yes
No need for codes from other websites. Yes
You can learn more how to code, I love teaching and can give you free tips! Yes
Familiarize yourself with the Facebook Graph API. Yes
Features are constantly improving, and you get it for free. Yes
Completely customizable. Yes

If you think there's a missing feature, please let us know by sending me a message via email mike@codeofaninja.com, or via our official Facebook page! We can work on it!

Thank you for supporting our projects here at codeofaninja.com!

16.4 Do You Want a Demo?

If you want a demo to see if this will work with your own Facebook page, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please provide your Facebook page URL on the message, thanks!

17.0 What's Next?

Today we have learned how to show your Facebook timeline feed on your website.

Did you know that you can also display Instagram feed on your website?

Let us go to the next tutorial: How To Display Instagram FEED on Website?

18.0 Related Source Codes

Did you know that you can also display other social media data on your website? I’ve created tutorials on them too, see the following:

Social Media Script Tutorials
Display Facebook Page EVENTS on Website
Display Facebook Page PHOTOS on Website
Display Facebook Page VIDEOS on Website
Display Facebook Page POSTS on Website
Display Instagram FEED On Your Website
Display Twitter FEED on Website
Display Google+ FEED on Website

19.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

  • 1. Subscribe to social media scripts tutorial news and updates.
  • 2. Be updated about what works and what does not work on social media APIs.
  • 3. Be notified for any related social media API updates.
100% Privacy. We will never spam you!

#3 Thank You!

Thanks for visiting our tutorial on how to display Facebook page posts on website using PHP and Facebook Graph API!

90 replies
    • ninjazhai
      ninjazhai says:

      @disqus_5mevFn3QMc:disqus, as long as Facebook provides the API, I will keep updating this code based on that API. Usually, FB updates their API every few years only.

  1. h1p
    h1p says:

    Hi. First of all: BIG THANX

    I’ve been searching and messing around with SDK, Composer, FB APIs,.. to achieve to place feeds in my FB page to appear on my website without any luck until now.

    Now it does work but in debugg mode I still get the following error messages:
    – Notice: Undefined offset: 1 in… ($picture_url = urldecode($picture_url_arr[1]);)
    – Notice: Undefined index: name in… ($name = $obj[‘data’][$x][‘name’];)
    – Notice: Undefined index: description in… ($description = $obj[‘data’][$x][‘description’];)

    Am I doing anything wrong? Any clue?

    T.I.A.,
    hip

  2. ninjazhai
    ninjazhai says:

    Sorry for the late reply, the Notice: Undefined means there’s no value on the variable you’re trying to access. You can try to use the isset() function to check if a variable has value.

    • ninjazhai
      ninjazhai says:

      Hello you guys, you can try to do it like this:

      $picture_url = urldecode(isset($picture_url_arr[1]) ? $picture_url_arr[1] : “”);
      $name = isset($obj[‘data’][$x][‘name’]) ? $obj[‘data’][$x][‘name’] : “”;
      $description = isset($obj[‘data’][$x][‘description’]) ? $obj[‘data’][$x][‘description’] : “”;

  3. Martin Pfeiffer
    Martin Pfeiffer says:

    Hi there, Mr. Ninja.
    Thanks for that guide and your effort. It is working great, after I understood how to use it ^^.
    One question:
    I’m grabbing the whole feed of a public Facebook timeline. There are some posts, who are just shared, so the original post is on another timeline.
    Those are displayed as “XYZ shared a status” and its link “View on Facebook”.
    Is there a way, to display the whole shared status in my feed?

    Regards,
    Tin

  4. Freddy Morán Jr.
    Freddy Morán Jr. says:

    This can be useful if you want to add an image in case of the type of publication was a video (for youtube only):

    *add this after the line “if($type==”status”){…….}”.

    else if($type==”video”){

    $parse_vurl = parse_str(parse_url($link,PHP_URL_QUERY), $get_from_var);

    $youtube_vid = $get_from_var[‘v’];

    echo “”;

    }

  5. Aykun Cetinkaya
    Aykun Cetinkaya says:

    This guy is the best. There was a small issue and he me helped right away. I recommend this script to everybody. Instead of wasting time by copy pasting, just purchased the package and saved a lot of time also it came with many ajax features.

  6. Pankaj Lohia
    Pankaj Lohia says:

    hello. Thanks for the code. works fine except that it wont display any pictures except pictures of posts taken from fb newsroom itself. what do i do for it to display the pictures of posts? The posts are hyperlinks and fb populates the picture by itself from those links.

  7. Pankaj Lohia
    Pankaj Lohia says:

    Hey, thank you for the code. It works fine except that I am unable to get pictures exctacted from the links i have posted on the fb page. The images are not displaying on the webpage except for one post which was taken from fb newsroom. How can i get the images to display? please help?

  8. Wannabe Dev
    Wannabe Dev says:

    I’m sorry to bother you. I’m new to coding so I thought of asking before diving into this adventure.
    The first part of step 3 seems vague to me and I can’t understand how to “create an app” as you suggest.

    The URL you show leads me to this message:

    {
    “error”: {
    “message”: “An unknown error has occurred.”,
    “type”: “OAuthException”,
    “code”: 1
    }
    }

  9. Antifaith
    Antifaith says:

    Hi, having an issue with the feed displaying content from another user posting on the page, how could I limit the feed to match only the authors ID from $fb_page_id?

    $obj[‘data’][$x][‘from’][‘id’];

      • Antifaith
        Antifaith says:

        https://www.facebook.com/Watersmeethotel1?fref=ts

        $found_post = false;

        for($x=0; $x<$feed_item_count; $x++){

        $fb_author_id = $obj['data'][$x]['from']['id'];

        if ($fb_author_id == $fb_page_id) {

        $found_post = true;

        break;

        }

        }

        if (! $found_post) {

        echo "";

        return;

        }

        Fixed it, though there was then an issue when they posted a link to something that bought up a thumbnail, and now when they've posted a facebook video, there's no fallbacks for not being able to deal with this data

  10. hafizh
    hafizh says:

    This code is amazing. I’m looking for use Facebook API without SDK, then i found this code. but, i have some issue about API. I had trying to open this API link (
    https://graph.facebook.com/141897xxxx/feed?access_token=150970xxxxxxxx&fields=id,message,picture,link,name,description,type,icon,created_time,from,object_id&limit=5) in my browser to get some feed in my facebook account, but it only look like this

    {
    “data”: [

    ]
    }

    The “data” shouldn’t empty. Is there any wrong with that link? sorry for bad english

  11. Yanek Yuk
    Yanek Yuk says:

    Great tutorial. But I have the problem of missing images also.

    The weird thing is there’s nothing wrong with the code. For instrance I can put ” “https://graph.facebook.com/{$fb_page_id}/picture?type=square” link into the adress bar while changing the “fb_page_id” and I can get to the square profile picture whether I am logged in or not, it doesn’t matter. But when the webpage I am using this on tries to do it, it doesn’t work. I am guessing it’s because of a non-granted permission. I hope someone has a solution for this.

    Thanks in advance.
    -Yanek

  12. Joshmar Steffens
    Joshmar Steffens says:

    Hello,

    I have a fiew questions reguarding the Basic source code that i bought from you (witch by the way is AWESOME exactly what i was looking for for a long time.)

    but i have some error’s:

    when i just run your pack without any changes it tells me

    Notice: Undefined index: description in C:xampphtdocstestsfacebook_postsindex.php on line 155

    Notice: Undefined index: object_id in C:xampphtdocstestsfacebook_postsindex.php on line 167

    Notice: Undefined index: comments in C:xampphtdocstestsfacebook_postsindex.php on line 233

    and some more undefined indexes when im changing the page id to the one i want to use.

    next to that the images from the like button and the comments button misses (I checked the link and it returns an emputy page)

    Thanks for all the coding its amazing work!

    -Joshmar

  13. Kris
    Kris says:

    On my website and your demo the images are nog loading in Firefox. It works perfect in Chrome and Safari. Any idea how to solve this?

    Update: Changed Firefox history setting from ‘Never remember history’ to ‘Remember history’ and now it works!

  14. Matt
    Matt says:

    So after six hours I finally solved the problem with other people showing up in your page feed. Simply replace feed with posts:

    “https://graph.facebook.com/{$fb_page_id}/feed?access_token={$access_token}&fields={$fields}&limit={$limit}”;

    “https://graph.facebook.com/{$fb_page_id}/posts?access_token={$access_token}&fields={$fields}&limit={$limit}”;

  15. Justin Webb
    Justin Webb says:

    Hi – I’m curious if it is possible with this code (or a few simple changes) to only pull certain posts from the page. For example, so posts are hashtaged “Marketing” and some are hashtaged “Design” and I only want to pull the ones that are hashtaged “Marketing” – BTW – YOU ROCK!

    • Mike Dalisay
      Mike Dalisay says:

      Hello @disqus_MM75W44AQA:disqus , thanks for the kind words! About your question, unfortunately our code cannot pull posts by hashtags. I remember it can be done in api version 1.0 before but this feature was gone in 2.0 onwards.

  16. Adrian
    Adrian says:

    My website doesn’t seem to update the latest news. has the same posts. The time updated doesn’t seem to change either. Weird thing is if i re upload the file it will update but it seems only in chrome. One the browsers it doesn’t update on if there is a video it says wrong mime type.. worked when i frist did it :(

  17. Gabriel Paquin
    Gabriel Paquin says:

    I like your website and your tutorials are very useful. Recently, I learn how to get the tweeter’s feed and also the instagram’s one because of you.

    But with the facebook’s feed, strangely when I try to get the JSON content, i have that error :
    (#100) Tried accessing nonexisting field (feed) on node type (Application)

    Do you know why?
    Thanks to answering!
    -Gab

  18. JamesB
    JamesB says:

    Great script, however I can’t seem to get any data to come out of the Graph API. I imagine I’ve not setup something correctly but all I get is the error below:
    “Object with ID ‘[XXXXCORRECT-FB-OBJ-IDXXX]’ does not exist, cannot be loaded due to missing permissions, or does not support this operation.”
    Do I need to set permissions up in the FB app configuration?
    I’ve looked around a lot, but can’t see anything that makes it obvious.
    Any help greatly appreciated!

  19. JamesB
    JamesB says:

    Looks like a really good script, however I’m having problems getting anything out of Facebook and I wonder if you could help.
    I’m created an App, and I’m using the correct access token (generated as your example) and the correct page ID, and yet all I get from the FB api is an error message :
    “Unsupported get request. Object with ID ‘[PAGE ID]’ does not exist, cannot be loaded due to missing permissions, or does not support this operation. ”
    Do I have to set any permission within the FB page or within the FB app that haven’t been mentioned within the tutorial?

  20. Satyam
    Satyam says:

    This code is working fine on my xampp local server, but as soon as i run it on my php live server, {post_id} is not tracked down. Can you please help me, its very urgent!

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.