How to display Facebook page posts on website using PHP?

Do you want to learn how to display Facebook page posts on your website? We have a new Facebook script for you!

This one is closely related to our previous Facebook 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 website. 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 different requirements, they want the Facebook feed to look different. The good news is, our code for today is a way to do it!

Don't want to code?

By the way, if you realized you do not want to code and you need more features, you can use a website plugin called SociableKIT.

You can easily customize the look and feel of your Facebook page posts feed and embed it on your website within a few clicks. See a tutorial here.

But if you like coding, continue with our tutorial below!

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.

Code Output

It is important to know where we are going. Once we finished the tutorial, we will achieve the output in the video below.

Enjoy the step-by-step tutorial below!

Create the index page

Create index.php file with basic HTML code

This index file will be loaded first and what we will see on the browser. Create index.php file. Put the following code.

<!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>Display Facebook page posts on website</title>

    <!-- CSS will be here -->

</head>
<body>
    <!-- Facebook page posts will be here -->
    <!-- JavaScript will be here -->
</body>
</html>

Include Bootstrap and custom CSS

Here we include Bootstrap CSS and our own custom CSS to make our page look good. Replace <!-- CSS will be here --> comment with the following code.

<!-- CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="custom.css" media="screen">

Include JavaScript

Include Bootstrap and Font Awesome JavaScript. Bootstrap JavaScript is required for Bootstrap to work better. We use Font Awesome for the likes and comments count icons. Replace <!-- JavaScript will be here --> comment with the following code.

<!-- JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/dd3a1aa24e.js" crossorigin="anonymous"></script>

Put code for Facebook page posts

Here's the body of our webpage. In this part, we will display the Facebook page posts. Replace <!-- Facebook page posts will be here --> comment with the following code.

<div class="container">
	<div class='col-lg-12'>
		<h1 class='page-header'>Display Facebook page posts on website</h1>
		
		<?php include "facebook_page_posts.php"; ?>

	</div>
</div>

Custom CSS

Create custom.css file

Create a custom.css file. This file was used inside the index.php file. Put the following code.

/* profile css will be here */

/* post css will be here */

/* other css will be here */

Profile CSS

The following CSS code is intended for profile information on the page. Replace /* profile css will be here */ comment with the following code.

.profile-info{
    overflow:hidden;
}

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

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

.profile-name{
    float:left;
    width:85%;
}

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

Post CSS

The following CSS code is for post information on the page. Replace /* post css will be here */ comment with the following code.

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

.post-content{
    background: #f6f7f9; 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;
}

Other CSS

These are other CSS codes used to make our web page look good. Replace /* other css will be here */ comment with the following code.

.page-header{
    margin:50px 0;
}

.time-ago{
    color:#999;
}

.like-count-summary{
    margin-top:10px;
}

Display Facebook page posts

Create facebook_page_posts.php file

This file will be used to be the central place where the Facebook page posts feed will be requested (from the Facebook Graph API), processed, and displayed. Create a facebook_page_posts.php file. This file was also used inside the index.php file. Put the following code.

<?php
include "functions.php";

// parameters will be here

// json link and contents will be here

// posts loop will be here
?>

Create functions.php

We have one function in this file. Its purpose is to convert a date and time value to a "time ago" format. For example 1 day ago, 2 hours ago, 1 month ago, etc. Create functions.php file. This file was used inside the facebook_page_posts.php file. Put the following code.

<?php
// 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';
}
?>

Parameters

These variables contains the parameters needed to make a request to the Facebook graph API. Replace // parameters will be here comment with the following code.

// prepare parameters
$fb_page_id = "YOUR_PAGE_ID";
$api_version = "v11.0";
$profile_photo_src = "https://graph.facebook.com/{$api_version}/{$fb_page_id}/picture?type=square";
$access_token = "YOUR_PAGE_ACCESS_TOKEN";
$fields = "id,attachments,message,picture,icon,created_time,from,story,likes.limit(0).summary(true),comments.limit(0).summary(true)";
$limit = 30;

Specify your Facebook page ID and token

You need to replace YOUR_PAGE_ID and YOUR_PAGE_ACCESS_TOKEN with your own. There are two ways to retrieve your page ID and token.

The first method is this: To get your Facebook page ID, follow this tutorial. To get your Facebook page access token, follow this tutorial. This method can be time-consuming.

We can do this process for you but there will be a service fee of $50. Also, you will need to make us an admin of your Facebook page. If you want to avail of this service, pay using this link. After the payment, you will receive further instructions from [email protected]

The second method this: We built and maintain a tool where you can easily retrieve your page ID and token. It costs $30. You can buy an access here. This method is faster and easier.

JSON link and contents

In this part, we will build the whole request link and get the response from the API. Replace // json link and contents will be here comment with the following code.

// build json link and get contents
$json_link = "https://graph.facebook.com/{$fb_page_id}/posts?fields={$fields}&limit={$limit}&access_token={$access_token}";
$json = file_get_contents($json_link);
$obj = json_decode($json, true);
$feed_item_count = count($obj['data']);

Loop through posts

Once we got the response or the data from the API, we will loop through it this way. Each loop contains a Facebook post from your page. Replace // posts loop will be here comment with the following code.

// loop throug posts
foreach($obj['data'] as $post){
    include "extract_values.php";
    include "display_values.php";
}

Extract values

Create extract_values.php file

Create extract_values.php file. This file was used inside facebook_page_posts.php file. Put the following code.

// post id, link, and page name will be here

// when it was posted will be here

// attachments will be here

// message and story will be here

// likes and comments count will be here

Extract post ID, link and page name

In this code, we will get the post ID and page name. We will also build the link to the original post on Facebook. Replace // post id, link, and page name will be here comment with the following code.

// post id, link, and page name
$id = isset($post['id']) ? $post['id'] : "";
$link = "https://www.facebook.com/{$id}";
$page_name = isset($post['from']['name']) ? $post['from']['name'] : "";

Extract post date

The following code retrieves the post date and time. We convert this value to a "time ago" value. Post date will look like this: 4 weeks ago. 3 days ago, 1 month ago, 2 years ago. We are using the time_elapsed_string() function from functions.php file in this part of the code. Replace // when it was posted will be here comment with the following code.

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

Extract attachments

We will get the post attachments. Attachments contains the post type, image or thumbnail, post title, and description. These data makes a post look more informative. Replace // attachments will be here comment with the following code.

// attachments
$att_type = "";
$att_title = "";
$att_description = "";
$att_image = "";
if(isset($post['attachments'])){
    $att_type = isset($post['attachments']['data'][0]['type']) 
        ? $post['attachments']['data'][0]['type'] : "";

    $att_title = isset($post['attachments']['data'][0]['title'])
        ? $post['attachments']['data'][0]['title'] : "";

    $att_description = isset($post['attachments']['data'][0]['description'])
        ? $post['attachments']['data'][0]['description'] : "";

    $att_image = isset($post['attachments']['data'][0]['media']['image']['src'])
        ? $post['attachments']['data'][0]['media']['image']['src'] : "";
}

Extract message and story

The $message variable contains the custom text entered by the user for the post. The $story variable contains values such as "added an even" or "updated their status". Replace // message and story will be here comment with the following code.

// message and story ("updated their status." or "added an event")
$message=isset($post['message']) ? $post['message'] : "";
$message=htmlspecialchars_decode(str_replace("\n", "<br>", $message));

$story = isset($post['story']) ? $post['story'] : "";

Extract likes and comments count

The likes and comments count are important signals of engagement. The following code is how we get these values. Replace // likes and comments count will be here comment with the following code.

// likes and comments count
$likes_count=isset($post['likes']['summary']['total_count'])
    ? $post['likes']['summary']['total_count'] : 0;

$comments_count=isset($post['comments']['summary']['total_count'])
    ? $post['comments']['summary']['total_count'] : 0;

Display values

Create display_values.php file

This file was also used inside facebook_page_posts.php file. Create display_values.php file. Put the following code.

<?php 
echo "<div class='item_box'>
    <div class='row'>";

        <!-- left side of the post will be here -->
        <!-- right side of the post will be here -->

    echo "</div>
    <hr />
</div>";

Display profile photo, story, post date, and message

The following code will display the page's profile photo, page name, date posted, and message. All on the right side of the post. Replace <! -- left side of the post will be here --> comment with the following code.

// left side
echo "<div class='col-md-4'>
    <div class='profile-info'>
    
        <div class='profile-photo'>
            <a href='https://fb.com/{$fb_page_id}' target='_blank'>
                <img src='{$profile_photo_src}' />
            </a>
        </div>

        <div class='profile-name'>
            <div>";
                echo !empty($story) ? $story : $page_name;
            echo "</div>
            <div class='time-ago'>{$ago_value}</div>
        </div>
    </div>

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

Display attachments, likes, and comments count

The following code will display the attachment image, title, and description on the right side of the post. There is a link to the post on Facebook. It will also display the likes and comments count. Replace <! -- right side of the post will be here --> comment with the following code.

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

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

                else{
                    echo "<div class='post-status'>
                        View on Facebook
                    </div>";
                }

                // if there's an attached title and description
                if($att_title && $att_description){
                    echo "<div class='post-info'>
                        <div class='post-info-name'>{$att_title}</div>
                        <div class='post-info-description'>{$att_description}</div>
                    </div>";
                }
            
        echo "</div>
    </a>

    <div class='like-count-summary'>
        <div style='float:left; margin:0 .6em 0 0;'>
            <i class='far fa-thumbs-up'></i> {$likes_count}
        </div>
        <div style='float:left;'>
            <i class='far fa-comments'></i> {$comments_count}
        </div>
    </div>
</div>"; 

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 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

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 with 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.

FEATURES BASIC
Do it once: post on your Facebook page and automatically show it on your website Yes
Save time studying and coding these features on your website Yes
Automatically show type of post, it can be status, link, video, etc. Yes
Posts are linked to your Facebook page. Engage your visitors to your Facebook page. Yes
Status post will have "View On Facebook" link Yes
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 3 months. Yes
Free source code updates. Yes
$50 - Download now

Do you need more reasons to download the source code?

MORE REASONS TO DOWNLOAD THE CODE
One-time payment. No need to buy a subscription. Yes
Buy only once, use on up to 5 websites and Facebook pages! Yes
No different kind of licenses. Yes
No many different pricing schemes. Yes
No monthly or yearly fees. Yes
No need to rely on another website to render Facebook timeline feeds Yes
No need for codes from other websites. Yes
Familiarize yourself with the Facebook Graph API. Yes
Completely customizable. Yes

Need help and support? email [email protected]

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

What's Next?

Today we have learned how to show your Facebook page posts 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 Facebook page events on website using PHP?

Related Tutorials

We have more tutorials related to social media APIs. Click here.

Some Notes

Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

Subscribe to CodeOfaNinja

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

Thank You!

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

Before you write a comment, please read this guide and our code of conduct.