Posts

How To Display Facebook Page Videos On Website Using PHP?

Let's code!

Do you have a video manager on your website? Do you upload videos on your Facebook page?

If your answer is both YES, you’re wasting a lot of time managing your brand's videos online.

What if there's a way to upload a video ONCE, and then let it appear both on your Website and Facebook page?

Will you be happy saving your precious time?

Our code for today will make you happy then, just like we are!

Today I'm gonna teach you how to display publicly available Facebook Page VIDEOS on your website.This one is great if you want your Facebook page videos to be shown in your website in a synchronized way.

Once you uploaded a video on Facebook, it will be automatically reflected on your website too.

Source Code Overview

Here’s an overview of what our code does:

Gets videos listed with data such as the video itself, video title, description, date posted, etc. from your Facebook fan page without using any Facebook PHP SDK, just the Facebook Graph API!

Display these videos to a webpage (assuming it is your WordPress or PHP website.)

Show some awesome UI powered by Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step by step Bootstrap tutorial here.

Display Facebook Page Videos on Website - Output

BASIC Source Code Output

We have to know where we are going, if we’re done with the code tutorial below, we will achieve this output:

PRO Source Code Output

We used PHP classes and so features are easier to use, more actively improved and added.

See the full list of features in section 10.1 to 10.3 below. It has all the details of these features.

For now, let us learn how the BASIC source code was made. Enjoy the following step by step tutorial!

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.

Create index.php

Create index.php and set the timezone, Facebook page and the page title. Put the following code inside index.php

<?php
// set timezone for servers that requires it
date_default_timezone_set("America/Los_Angeles");

// set Facebook page ID or username
$fb_page_id = "katyperry";

// page title
$page_title = "BASIC - Display Facebook Page Videos on Website";
?>

Enable Bootstrap

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

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

    <meta charset="utf-8">
    <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> <!-- /container -->

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

Specify Variables

Specify the values for the following variables:

  • $profile_photo_src so that the Facebook page primary picture will be rendered in thumbnail.
  • $access_token obtained on section 3.0, this will give us the power to get Facebook page videos.
  • $fields are actually column names in Facebook page videos database.
  • $limit the number of videos you want to be displayed on your page.

Put the following code inside the 'container' tags on section 5.0

$profile_photo_src = "https://graph.facebook.com/{$fb_page_id}/picture?type=square";
$access_token = "YOUR_ACCESS_TOKEN ";
$fields = "id,title,description,created_time,from,source";
$limit = 5;

Build JSON Link

Use the variable values on the previous section and construct the $json_link. Get the data from that URL, decode it, and count the number of records it returned.

In short, put the following code after the code in section 6.0

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

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

Loop Through Videos

Loop through each records, extract each video information and place it in an HTML structure.

for($x=0; $x<$feed_item_count; $x++){
	echo "<div class='row'>";
		// video source
		$source = $obj['data'][$x]['source'];

		// display Facebook page video
		echo "<lt;div class='col-md-6'>";
			echo "<video controls class='embed-responsive-item'>;
				echo "<source src={$source} type=video/mp4>";
			echo "</video>";
		echo "</div>";

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

			// user's custom message
			$title = isset($obj['data'][$x]['title'])
						? htmlspecialchars_decode($obj['data'][$x]['title'])
						: "Video #" . $obj['data'][$x]['id'];

			$description = isset($obj['data'][$x]['description']) ? $obj['data'][$x]['description'] : "";
			$description = htmlspecialchars_decode(str_replace("\n", "<br>", $description));

			// 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_id = $obj['data'][$x]['from']['id'];
			$page_name = $obj['data'][$x]['from']['name'];

			// display video title
			echo "<h2 style='margin: 0 0 .5em 0;'>{$title}</h2>";

			// display video description
			echo "<div>";
				echo $description;
			echo "</div>";

			// display when it was posted
			echo "<div style='margin:.5em 0 0 0; color: #999;'>";
				echo "Posted {$ago_value} by <a href='https://facebook.com/{$page_id}' target='_blank'>{$page_name}</a>";
			echo "</div>";

		echo "</div>";

		echo "<div class='col-md-12'>";
			echo "<hr style='margin:2em 0; border:thin solid #f1f1f1;' />";
		echo "</div>";
	echo "</div>";
}

Format Post Date

time_elapsed_string() is a function that will return the "time ago" value, from section 8.0, we pass when the video was posted so that we can display something like: 9 days ago, 9 months ago, a year ago, etc...

Put the following code after the closing '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';
}

Download the Complete Source Code

You can get the source code for free 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.

Download BASIC Source Code

FEATURES BASIC
Upload videos on your Facebook page, watch them on your website. YES
Save time figuring out and coding these features on your website. YES
Display video list from your Facebook page. YES
Display video title. If none, display video number. YES
Display video description. YES
Post date with "time ago" format. YES
Display Facebook page name (with link) for each video. (opens in new tab) YES
Bootstrap enabled script. YES
Responsive layout. (great for mobile devices) YES
Free source code updates. YES
Free support for 6 months. YES
Download Now

Download the PRO Source Code

All features of BASIC source code. YES
Display number of likes. YES
Display number of comments. YES
Display some likers and link to their profiles. YES
Display commenters and link to their profile. YES
Display user comments. YES
Show comments and comment replies on pop up. YES
Load more videos automatically when scrolling (infinite scroll). YES
Newly loaded content still has video controls, number of likes, etc. YES
Will say "All videos were loaded." when there’s no content to be loaded. YES
Make links clickable in video description. YES
Make links clickable in user comments. YES
Link to actual Facebook page video post. YES
Likers and commenters are loaded and shown via AJAX YES
Show comments YES
Show more comments, loaded via AJAX YES
Show comment replies YES
Show more comment replies, loaded via AJAX YES
Made with PHP classes YES
Useful class methods & properties YES
4-step easy integration to your website YES
Free support for 1 year. YES
Free source code updates. YES
Download Now

Need more reasons to download?

MORE REASONS TO DOWNLOAD IT
Buy only once, use on unlimited number of 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 page videos. 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
You get free code and feature updates YES
Tutorial above is always free and updated every Facebook API update. YES
Completely customizable. YES

If you think there's a missing feature, please let us know by sending me a message via email [email protected], or via our official Facebook page! We can work on it!

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

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

What's Next?

Today we have learned how to show your Facebook page videos on your website.

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

Let us go to the next tutorial: How To Display Facebook Page POSTS on Website?

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

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 [email protected], 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 videos on website using PHP and Facebook Graph API!

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!

How to display Facebook page events on website using PHP?

Do you want to learn how to display Facebook page events on your website? What if there's a way to create an event once, and then let it appear both on your website and Facebook page?

Today we're gonna talk about how to display publicly available Facebook Page events on your website. This one is great if you want your Facebook page events to be shown on your website in a synchronized way.

Once you created or updated an event on Facebook, it will be automatically reflected on your website too.

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

Here's an overview of what our code does:

Gets events listed with data such as event image, name, time, description, etc. from your Facebook fan page without using any Facebook PHP SDK, just the Facebook Graph API!

Display these event data to a webpage (assuming it is your WordPress or PHP website.)

Show some awesome UI powered by Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step-by-step Bootstrap tutorial here.

Final output

We have to know where we are going. If we completed the tutorial below, we will achieve the following output in the video below.

Create the index page

Create index.php file

This page is what will be loaded on the browser. Create index.php file. Put the following basic HTML 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 events on website</title>

    <!-- CSS will be here -->
 
</head>
<body>

    <!-- Container will be here -->

</body>
</html>

CSS code

We're going to use Bootstrap to make our page look good. We'll also put some custom CSS. Replace <!-- CSS will be here --> 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">

Create custom.css

These are just some additional customization for our user interface. Create a custom.css file. Put the following code.

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

.nav{
    margin-bottom:30px;
}

.event_item{
    margin-bottom:50px;
}

Container code

These divs have Bootstrap classes. It will contain our Facebook page events. Replace <!-- Container will be here --> with the following code.

<div class="container">
    <div class='col-lg-12'>
        <h1 class='page-header'>Display Facebook page events on website</h1>
        
        <!-- PHP code will be here -->

    </div>
</div>

PHP code

The code below gets the parameter from the URL about what to display. By default, it is "upcoming" events. The navigation.php file will help the user to select upcoming or past events.

The fb_page_events.php file will contain our request to the Facebook Graph API. Replace <!-- PHP code will be here --> with the following code.

<?php 
$display = isset($_GET["display"]) ? $_GET["display"] : "upcoming";
include "navigation.php";
include "fb_page_events.php";
?>

Create navigation.php file

This file will show two tabs that will allow our users to select upcoming or past events. Create a navigation.php file and put the following code.

<?php 
$upcoming_class_active = $display=="upcoming" ? "active" : "";
$past_class_active = $display=="past" ? "active" : "";

echo "<ul class='nav nav-tabs'>
    <li class='nav-item'>
        <a class='nav-link {$upcoming_class_active}' href='index.php'>Upcoming Events</a>
    </li>
    <li class='nav-item'>
        <a class='nav-link {$past_class_active}' href='index.php?display=past'>Past Events</a>
    </li>
</ul>";
?>

Display Facebook page events

Create fb_page_events.php file

This file will contain the process of building a request to the Facebook Graph API. Create fb_page_events.php file. Put the following code.

<?php 
// specify date range will be here

// unix timestamp format will be here

// request parameters will be here

// build the api request will be here

// sort to display upcoming events will be here

// looping through events will be here
?>

Specify date range

The code below identifies the "since" and "until" dates that will be used for the API request. For upcoming events, the "since" date is the date today and the "until" date is two years from today.

For past events, the "since" date is the date from two years ago and the "until" date is the date yesterday.

Replace <!-- specify date range will be here --> with the following code.

// specify date range
$year_range = 2;

if($display=="upcoming"){
	// date range for upcoming events
	$since_date = date('Y-m-d');
	$until_date = date('Y-12-31', strtotime('+' . $year_range . ' years'));
}

else{
	// date range for past events
	$since_date = date('Y-01-01', strtotime('-' . $year_range . ' years'));
	$until_date = date('Y-m-d', strtotime('-1 day'));
}

Convert to unix timestamp

Unix timestamp is required by the Facebook Graph API. We will convert the since and until dates using the code below. Replace <!-- unix timestamp format will be here --> with the following code.

// unix timestamp format
$since_unix_timestamp = strtotime($since_date);
$until_unix_timestamp = strtotime($until_date);

Specify request parameters

The variables below are needed to complete the parameters needed for the Facebook Graph API request. Replace <!-- request parameters will be here --> with the following code.

// request parameters
$api_version = "v11.0";
$fb_page_id = "YOUR_FACEBOOK_PAGE_ID";
$access_token="YOUR_PAGE_ACCESS_TOKEN";
$fields="id,name,description,place,timezone,start_time,cover";

Specify your Facebook page ID and access token

You need to replace YOUR_PAGE_ID and YOUR_PAGE_ACCESS_TOKEN with your own.

To get your Facebook page ID, follow this tutorial. To get your Facebook page access token, follow this tutorial.

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]

Build the API request

The code below completes the API request link and get the response using file_get_contents() function. We will also decode the response so we can easily retrieve the data. Replace <!-- build the api request will be here --> with the following code.

// build the api request
$json_link = "https://graph.facebook.com/{$api_version}/{$fb_page_id}/events/attending/?fields={$fields}&access_token={$access_token}&since={$since_unix_timestamp}&until={$until_unix_timestamp}";
$json = file_get_contents($json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);

// for those using PHP version older than 5.4, use this instead:
// $obj = json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $json), true);

Sort to display upcoming events

Sorting is needed to properly display the upcoming events. The code below will let the upcoming events to be displayed from the date nearest to today up to the farthest date. Replace <!-- sort to display upcoming events will be here --> with the following code.

// sort to display upcoming events
if($display=="upcoming"){
	function sortFunction($a,$b){
		if ($a['start_time'] == $b['start_time']) return 0;
		return strtotime($a['start_time']) - strtotime($b['start_time']);
	}
	usort($obj['data'],"sortFunction");
}

Loop through events

The code below will loop through each events returned from the Facebook Graph API. Replace <!-- looping through events will be here --> with the following code.

// looping through events
foreach($obj['data'] as $event){
	include "extract_values.php";
	include "display_values.php";
}

Extract and display events data

Create extract_values.php file

In this file, we will extract different types of event data. Create extract_values.php file. Put the following code.

<?php 
// start date and time will be here

// basic info will be here

// location will be here
?>

Extract date and time

The code below will let us get the event's start date and time. Replace <!-- start date and time will be here --> with the following code.

// start date and time
$timezone=isset($event['timezone']) ? $event['timezone'] : "America/Los_Angeles";
date_default_timezone_set($timezone);

$start_date = date( 'l, F d, Y', strtotime($event['start_time']));

// in my case, I had to subtract 9 hours to sync the time set in facebook
$start_time = date('g:i a', strtotime($event['start_time']));

Extract basic information

The code below will let us get the event ID, name, description, and thumbnail. Replace <!-- basic info will be here --> with the following code.

// basic info
$eid = $event['id'];
$name = $event['name'];
$description = isset($event['description']) ? $event['description'] : "";
$pic_big = isset($event['cover']['source']) ? $event['cover']['source'] : "https://graph.facebook.com/{$api_version}/{$fb_page_id}/picture?type=large";

Extract location

Here we will get the event's complete address or location. Replace <!-- location will be here --> with the following code.

// location
$place_name = isset($event['place']['name']) ? $event['place']['name'] : "";
$city = isset($event['place']['location']['city']) ? $event['place']['location']['city'] : "";
$country = isset($event['place']['location']['country']) ? $event['place']['location']['country'] : "";
$zip = isset($event['place']['location']['zip']) ? $event['place']['location']['zip'] : "";

$location="";

if($place_name){ $location.="{$place_name}"; }
if($city){ $location.= $location ? ", {$city}" : "{$city}"; }
if($country){ $location.= $location ? ", {$country}" : "{$country}"; }
if($zip){ $location.= $location ? ", {$zip}" : "{$zip}"; }

if(empty($location)){
    $location="Location not set.";
}

$complete_event_add="{$location}";

Create display_values.php

The code below will let us display an event item with data we extracted earlier. Create display_values.php file. Put the following code.

<?php 
echo "<div class='row event_item'>
    <div class='col'>
        <img src='{$pic_big}' class='card-img-top' alt='...'>
    </div>
    <div class='col'>
        <h2 class='card-title'>{$name}</h2>
        <p class='card-text'>
        {$start_date} at {$start_time}
        </p>

        <p class='card-text'>
        {$complete_event_add}
        </p>

        <p class='card-text'>
        {$description}
        </p>
        <a href='https://www.facebook.com/events/{$eid}/' target='_blank' class='btn btn-primary'>More info</a>
    </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!

From Blog Comments

★★★★★ "Hi Mike, amazing tutorial." ~ simonerama

★★★★★ "Hello and THANK you for this amazing work! :)" ~ Sergio

★★★★★ "Did the trick for me. Thanks for the nice script!" ~ n0Fear

★★★★★ "Hi Mike, thanks for the great script. I'm a programming novice, but got this running the way I wanted to pretty quickly. I owe you a beer." ~ Bas Koole

★★★★★ "Hi it's working great :)" ~ Sebastian

From Emails

★★★★★ "I've got it working! You're a great man, will do some ad for you!" ~ Markus

★★★★★ "Hi Mike! BOOM, works great! Thanks again!" ~ Nick

★★★★★ "Perfect! Thank you very much! If I have some new jobs, I will contact you! Greetings from Germany." ~ Eric

★★★★★ "Thank you for the fast reply, yes this should work for me. I will contact you again. Thank you so much." ~ Ruocco

From Facebook Messages

★★★★★ "Hey Mate, code's a lifesaver (and time saver!)" ~ Andrew

★★★★★ "Thanks, I've been trying to get Facebook events on the website for 6+ months had no luck, decided last night to update the site which I haven't done in a while and thought I'd give it another go and found you're page through a google search." ~ Ward

★★★★★ "Mike it's great and simple! I like! Thank you!" ~ Jasmin

★★★★★ "You're a life saver, thanks so much." ~ Brendon

Download the Complete 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.

FEATURES BASIC
Manage events for your Facebook Page and website once Yes
Save time figuring out and coding these features on your website Yes
Display list of all events Yes
Display list of upcoming events Yes
Display list of past events Yes
Display event cover photo (profile picture if none) Yes
Display event title Yes
Display event date and time Yes
Display event location Yes
Display event description Yes
Link to actual Facebook page event (opens in new tab) Yes
Bootstrap UI enabled Yes
Responsive layout (great for mobile devices) Yes
Free email support for 6 months. Yes
Free source code updates. Yes
$50 - Download now

Do you need more reasons to download it?

MORE REASONS TO GET IT
Buy only once, use up to 10 websites and Facebook pages! Yes
No different kind of licenses. Yes
No monthly or any recurring fees. Yes
No need to rely on another website to render Facebook page events. 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
Tutorial above is always free. Yes
Completely customizable. Yes

Thank you for supporting our projects!

What's Next?

Today we have learned how to show your Facebook page events on your website.

Did you know that you can also display Facebook photo albums and photos on your website?

Let us go to the next tutorial: How to display Facebook page photo album on website?

Related Source Codes

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 events on website using PHP and Facebook Graph API!

How To Display Facebook Page Photo Albums on Website Using PHP?

Let's code!

Do you have a photo manager on your website? Do you upload photos on your Facebook page as well?

If your answer is both YES, you're wasting a lot of time managing your brand's photos online.

What if there's a way to upload your photo albums ONCE, and then let it appear both on your Website and Facebook page?

Will you be happy saving your precious time?

Our code for today will make you happy then, just like we are!

Today we're gonna display Facebook Page photos on your website (publicly available photos, without any kind of restrictions)!

Our source code is useful if you want your Facebook pictures to be shown in your website in a synchronized way.

Once you uploaded an image in your fan page, it will be seen automatically in your website too.

Let's get started!

Source Code Overview

Today we’re going to do a code that:

1. Gets photo albums and photos of a Facebook fan page (using Facebook Graph API).

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

3. Use Bootstrap Image Gallery extension to make awesome image pop up presentation. This extension is fully responsive and touch enabled. Good for every mobile device!

Advantages and Risks

This technique has the following advantages and risks.

Advantages

  1. You save server disk space because the photos don't reside in your hosting provider.
  2. You got instant photo manager which Facebook photos. It become's awesome and new features are added frequently.
  3. You save bandwidth since the photos shown in your website are loaded from Facebook’s repository.
  4. Please add your comment if you know other advantages.

Risks

  1. When Facebook is down, your website with this feature will be down as well. But I almost never encounter Facebook was down.
  2. Facebook is not responsible if you lost your data or any disruptions on it Read section 16.3 of their legal terms.
  3. Please add your comment if you know other disadvantages or risks.

Display Facebook Photos on Website - Output

It is important to know where we are going. The output of our step by step code tutorial will look like the the BASIC source code. See output preview below.

3.1 BASIC Source Code - Output Preview

[espro-slider id=6221]

PRO Source Code - Output Preview

[espro-slider id=6244]

The PRO source code outputs proves that you can add and customize more features. It’s easier and faster if you will learn by following our tutorial below.

Downloading our source codes is your huge advantage as well. For now, let’s proceed to the step by step tutorial of our BASIC source code. Enjoy!

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.

Create index.php with Basic HTML Code

Create index.php and with the following basic HTML code.

<?php
$page_title = "Photo Albums";
?>
<!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">
    <style>
    .col-md-4{
        margin: 0 0 2em 0;
    }
    </style>
</head>
<body>
 
<div class="container">
 
</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>

Build and Decode Photo Albums JSON link

Inside the DIV with a "container" class, put the page title, specify the Facebook page ID and decode the JSON string from a graph API URL.

<?php
echo "<div class='col-lg-12'>";
    echo "<h1 class='page-header'>{$page_title}</h1>";
echo "</div>";
 
$access_token="YOUR_ACCESS_TOKEN";
 
$fields="id,name,description,link,cover_photo,count";
$fb_page_id = "221167777906963";
 
$json_link = "https://graph.facebook.com/v2.8/{$fb_page_id}/albums?fields={$fields}&access_token={$access_token}";
$json = file_get_contents($json_link);
 
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
 
$album_count = count($obj['data']);
?>

Retrieve Photo Albums

Loop through the retrieved content. Put the following code under $album_count variable on step 2 above. It links to another PHP file called photos.php where the user can view the photos inside the album.

for($x=0; $x<$album_count; $x++){
 
    $id = isset($obj['data'][$x]['id']) ? $obj['data'][$x]['id'] : "";
    $name = isset($obj['data'][$x]['name']) ? $obj['data'][$x]['name'] : "";
    $url_name=urlencode($name);
    $description = isset($obj['data'][$x]['description']) ? $obj['data'][$x]['description'] : "";
    $link = isset($obj['data'][$x]['link']) ? $obj['data'][$x]['link'] : "";
 
    $cover_photo = isset($obj['data'][$x]['cover_photo']['id']) ? $obj['data'][$x]['cover_photo']['id'] : "";
 
    // use this for older access tokens:
    // $cover_photo = isset($obj['data'][$x]['cover_photo']) ? $obj['data'][$x]['cover_photo'] : "";
     
    $count = isset($obj['data'][$x]['count']) ? $obj['data'][$x]['count'] : "";
 
    // if you want to exclude an album, just add the name on the if statement
    if(
        $name!="Profile Pictures" &&
        $name!="Cover Photos" &&
        $name!="Timeline Photos"
    ){
 
        $show_pictures_link = "photos.php?album_id={$id}&album_name={$name}";
 
        echo "<div class='col-md-4'>";
            echo "<a href='{$show_pictures_link}'>";
                echo "<img class='img-responsive' src='https://graph.facebook.com/v2.3/{$cover_photo}/picture?access_token={$access_token}' alt=''>";
            echo "</a>";
            echo "<h3>";
                echo "<a href='{$show_pictures_link}'>{$name}</a>";
            echo "</h3>";
 
            $count_text="Photo";
            if($count>1){ $count_text="Photos"; }
 
            echo "<p>";
                echo "<div style='color:#888;'>{$count} {$count_text} / <a href='{$link}' target='_blank'>View on Facebook</a></div>";
                echo $description;
            echo "</p>";
        echo "</div>";
    }
}

Create photos.php with GET request

Create photos.php with the following PHP code the retrieves value from a GET request. We'll get the album ID and Name that can be used to the page title.

<?php
$album_id = isset($_GET['album_id']) ? $_GET['album_id'] : die('Album ID not specified.');
$album_name = isset($_GET['album_name']) ? $_GET['album_name'] : die('Album name not specified.');
 
$page_title = "{$album_name} Photos";
?>

Basic HTML Code for photos.php

Under the code on step 4 above, put the following basic HTML 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><?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>
 
<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>

Enable Image Gallery Lightbox

We'll include the Blueimp gallery extension so we can view our photos beautifully. Our basic HTML code will look like 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><?php echo $page_title; ?></title>
 
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
 
    <!-- blue imp gallery -->
    <link rel="stylesheet" href="http://blueimp.github.io/Gallery/css/blueimp-gallery.min.css">
    <link rel="stylesheet" href="Bootstrap-Image-Gallery-3.1.1/css/bootstrap-image-gallery.min.css">
 
    <style>
    .photo-thumb{
        width:214px;
        height:214px;
        float:left;
        border: thin solid #d1d1d1;
        margin:0 1em 1em 0;
    }
 
    div#blueimp-gallery div.modal {
        overflow: visible;
    }
    </style>
</head>
<body>
 
<div class="container">
 
</div>
 
<!-- The Bootstrap Image Gallery lightbox, should be a child element of the document body -->
<div id="blueimp-gallery" class="blueimp-gallery">
    <!-- The container for the modal slides -->
    <div class="slides"></div>
    <!-- Controls for the borderless lightbox -->
    <h3 class="title"></h3>
    <a class="prev">‹</a>
    <a class="next">›</a>
    <a class="close">×</a>
    <a class="play-pause"></a>
    <ol class="indicator"></ol>
    <!-- The modal dialog, which will be used to wrap the lightbox content -->
    <div class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" aria-hidden="true">×</button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body next"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default pull-left prev">
                        <i class="glyphicon glyphicon-chevron-left"></i>
                        Previous
                    </button>
                    <button type="button" class="btn btn-primary next">
                        Next
                        <i class="glyphicon glyphicon-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
    </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>
 
<script src="http://blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<script src="Bootstrap-Image-Gallery-3.1.1/js/bootstrap-image-gallery.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]-->
 
<!-- to make photos full view -->
<script>
$('#blueimp-gallery').data('useBootstrapModal', false);
$('#blueimp-gallery').toggleClass('blueimp-gallery-controls', true);
</script>
 
</body>
</html>

Build and Decode Photos JSON link

Inside the DIV tag with a "container" class, put the page title HTML, specify the JSON url and decode the JSON string.

<?php
echo "<h1 class='page-header'>";
    echo "<a href='index.php'>Albums</a> / {$page_title}";
echo "</h1>";
 
$access_token="your access token";
$json_link = "https://graph.facebook.com/v2.3/{$album_id}/photos?fields=source,images,name&access_token={$access_token}";
$json = file_get_contents($json_link);
 
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
 
$photo_count = count($obj['data']);
?>

Retrieve Photos

After the $photo_count variable on the code above, loop through the values using the code below:

for($x=0; $x<$photo_count; $x++){
 
    // $source = isset($obj['data'][$x]['source']) ? $obj['data'][$x]['source'] : "";
    $source = isset($obj['data'][$x]['images'][0]['source']) ? $obj['data'][$x]['images'][0]['source'] : ""; //hd image
    $name = isset($obj['data'][$x]['name']) ? $obj['data'][$x]['name'] : "";
 
    echo "<a href='{$source}' data-gallery>";
        echo "<div class='photo-thumb' style='background: url({$source}) 50% 50% no-repeat;'>";
 
        echo "</div>";
    echo "</a>";
 
}

How to Display Likes and Comments?

The feature of displaying the number of likes and comments and actual comments is now included in our PRO source code.

What People Say About This Code?

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

★★★★★ "The code works beautifully. I had no problems... Great code. DONATE TO THIS SITE!" ~ jdogfantastic

★★★★★ "Ninja Mike, this wonderful tutorial has allowed me to do something totally over my head. Thank you!" ~ Handy

★★★★★ "Hey this is a great and useful script! I've managed to change some stuff around as I wanted to show photos from a specific album..." ~ Konstantinos

★★★★★ "Hi Mike, this is really... really... great work dude. You really helped me out today. I added my own twist of incorporating it into AJAX as well. I will post my version of the code." ~ Paul

★★★★★ "THANK YOU SO MUCH! I've been searching and struggling to create a new way for my web customers to organize their own photos on their websites, and this is perfect!!!" ~ Little Doe

★★★★★ "Hi, I"m doing a website for an NGO that helps cancer patients and I've used part of your script to display Facebook photos. Great work, btw." ~ Will

★★★★★ "Hi Mr. Dalisay, My name is Clinton and I'm a front-end designer. I purchased two scripts from you today. Thank you for your time and what a great tutorial and was happy to support your projects." ~ Clinton

★★★★★ "Thanks for the excellent support..." ~ Horatio

Download Source Code

You can get the source code by following the whole, step by step 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 and 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.

Download BASIC Source Code

FEATURES BASIC
Manage photos on your Facebook page and website only once Yes
Save time figuring out and coding these features on your website Yes
Display list of photo albums Yes
Display album cover Yes
Display album description Yes
Display number of photos inside an album Yes
Link to actual Facebook album page (opens in new tab) Yes
Clicking a photo album will show list of photos Yes
Each photo are in a square thumbnail Yes
Clicking a photo will pop a lightbox Yes
Navigate photos using the lightbox's Next and Prev buttons Yes
Responsive photo albums page Yes
Responsive photos page Yes
Responsive lightbox pop up window Yes
Touch-enabled lighbox gallery (great for smartphone and tablet devices) Yes
Bootstrap UI enabled Yes
Free source code updates. Yes
Free email support for 6 months. Yes
Download Now

Download PRO Source Code

FEATURES PRO
All features of the BASIC source code Yes
Can show more than 25 photo albums Yes
Can show more than 25 photos Yes
Load more photo albums automatically when scrolling Yes
Load more photos automatically when scrolling Yes
Will say "All photo albums were loaded." if no albums to be shown. Yes
Will say "All photos were loaded." if no photos to be shown. Yes
Photo album cover automatically cropped to certain size Yes
No need to make each photo album cover the same size Yes
Font awesome icons Yes
Share buttons on photos page Yes
Object-oriented programming YES
Display comments of photo albums YES
Load more comments of photo albums YES
Display comments of photos YES
Load more comments of photos YES
Count number of comments of each person YES
Display image comments YES
Useful variables you can change in /libs/php/dsm_facebook_photos.php
$fb_graph_api_version
to easily change Facebook Graph API version.
YES
$limit
to easily change default number of photo albums and photos shown
YES
$hidden_albums
to easily hide photo albums.
YES
$access_token
to easily change to your own access token
YES
How to display PHOTO ALBUMS using the PRO source code?
1. Once you extracted the files,
copy the folder 'display-facebook-photos-pro' in your root directory.
YES
2. Put the following code at the beginning of you PHP file.

 

include_once
"display-facebook-photos-pro/libs/php/dsm_facebook_photos.php";
$dsm_facebook_photos = new DsmFacebookPhotos();
YES
3. Put the following code inside head section.

 

echo $dsm_facebook_photos->printCSS_DsmPhotoAlbums();
YES
4. Put the following code where you want the feed to appear.

 

echo $dsm_facebook_photos->readPhotoAlbums_Dsm();
YES
5. Put the following code before the closing body tag.

 

echo $dsm_facebook_photos->printJavaScript_DsmPhotoAlbums();
YES
How to display PHOTOS using the PRO source code?
1. Once you extracted the files,
copy the folder 'display-facebook-photos-pro' in your root directory.
YES
2. Put the following code at the beginning of you PHP file.

 

include_once
"display-facebook-photos-pro/libs/php/dsm_facebook_photos.php";
$dsm_facebook_photos = new DsmFacebookPhotos();
YES
3. Get parameter values. Put the following code next.

 

$album_id = isset($_GET['album_id']) ? $_GET['album_id']
            : die('Album ID not specified.');
$fb_page_id = isset($_GET['fb_page_id']) ? $_GET['fb_page_id']
            : "221167777906963";
YES
4. Set parameter values as properties. Put the following code next.

 

$dsm_facebook_photos->album_id=$album_id;
$dsm_facebook_photos->fb_page_id=$fb_page_id;
YES
5. Get album details. Put the following code next.

 

$album_details=$dsm_facebook_photos->readAlbumDetails_Dsm();
YES
6. Set page title. Put the following code next.

 

$page_title = "{$album_details['name']}";
YES
7. Put page title inside title tags.

 

<?php echo $page_title; ?>
YES
8. Put the following before the closing head tag.

 

echo $dsm_facebook_photos->printCSS_DsmPhotos();
YES
9. Display photos inside album.
Put the following code anywhere in the body.

 

echo $dsm_facebook_photos->readContents_DsmFacebookPhotos();
YES
10. Put the following codes before the closing body tag.

 

echo $dsm_facebook_photos->printJavaScript_DsmPhotos();
YES
Download Now

Do you need more reasons to download it?

MORE REASONS TO DOWNLOAD IT
Buy only once, use 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 photo albums and photos. 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

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

SociableKIT

You demanded it, we built it. A lot of people requested a website plugin version of this Facebook gallery code. Now it is available. It works no matter what website platform you use. We have tried it in WordPress, Squarespace, Wix and more.

What's Next?

Today we have learned how to show your Facebook photo albums and photos on your website.

Did you know that you can also display Facebook videos on your website?

Let us go to the next tutorial: How To Display Facebook VIDEOS on Website?

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

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 [email protected], 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!

Thank you for reading our tutorial on how to display Facebook photos on website using PHP!