Download The Social Media Scripts – LEVEL 3 – PRO PACK

social media script level 3 pro pack
Here in codeofaninja.com, we work hard to produce scripts that works - scripts that are truly useful for your projects or business.

Downloading this LEVEL 3 PRO PACK now will give you the same features and quality support as if you buy them one by one. The only difference is you get a huge discount.

This pack contains five LEVEL 3 social media scripts we have. If you will buy them all one by one, it will cost you $249.95.

But, if you will download this pack, it will be $198 only. You just saved $51.95!

Social Media Scripts - LEVEL 3 - PRO PACK
ITEM Original Cost LEVEL 3 PRO PACK
Display Facebook EVENTS on Website $49.99 YES
Display Facebook PHOTOS on Website $49.99 YES
Display Facebook VIDEOS on Website $49.99 YES
Display Facebook FEED on Website $49.99 YES
Display Instagram FEED On Your Website $49.99 YES
BUY TO DOWNLOAD PRO PACK NOW FOR ONLY $249.95 $198

Not convinced?

If you will buy our LEVEL 3 PRO PACK now, you will get two LEVEL 2 scripts as well! These scripts are worth another $59.98 and you get it at no extra cost!

This time, instead of spending $309.93, you still get it for $198. You just saved $111.93!

Get these scripts as well!
ITEM Original Cost LEVEL 3 PRO PACK
Display Twitter FEED on Website $29.99 YES
Display Google+ FEED on Website $29.99 YES
BUY TO DOWNLOAD PRO PACK NOW FOR ONLY $309.93 $198

What People Say About Our Social Media Scripts?

★★★★★ “Hi Mr. Dalisay, My name is Clinton and I’m a front end designer. I purchased two (Facebook) scripts from you today. Thank you for your time and what a great tutorial and was happy to support your projects.”

 

Clinton Moore
Web Developer & Owner, Netchanics

 

 

 

★★★★★ “This guy is the best. There was a small issue and he helped me right away. I recommend this (Facebook Feed) script to everybody. Instead of wasting time by copy pasting, just purchased the package and saved a lot of time.”

 

Aykun Cetinkaya
Media Representative, LinkedIn Profile

 

 

 

★★★★★ “Just wanted to say thank you. Just purchased the (Social) Script PRO Pack today not too long ago and modified it a bit to make it a dark theme and it’s working great. It saved me A LOT of time! Thank you!!!!!!!”

 

Daniel Mort
Web Developer & Owner, Morthub

 

 

 

Are you a previous buyer?

If you previously bought any scripts here in codeofaninja.com, we'll give you another 15% off today!

Just send me an email ([email protected]) with a subject "DISCOUNT REQUEST: Social Media Scripts – LEVEL 3 – PRO PACK" and I'll reply with the discount code.

You don't like to code? No problem!

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

Thank you for supporting codeofaninja.com!

If you have any questions or if there's anything else I can help you with, please do not hesitate to send me an email. My email address is [email protected]

You can use the comment box below as well.

How To Display Twitter Feed 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.

Need to embed a Twitter hashtag feed on your website? Watch this tutorial.

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

Let's code!

Do you actively use Twitter for your brand or products? Does your client use it?

If you use it for your brands or products and you have your own website, it will be a great feature if you can display your twitter feed or posts on your website.

I know, you can embed your Twitter feed using the Twitter widget, but you cannot customize the look and feel.

It looks like the default Twitter interface.

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

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

Source Code Overview

Here’s an overview of what our code does:

  1. It gets a Twitter users's profile information and posts from a specified twitter account. We'll try Taylor Swift's twitter account in the demo.
  2. Display these Twitter data to a webpage (assuming it is your WordPress or PHP website.)
  3. 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 Demo

LEVEL 1 Source Code Output

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

display-twitter-feed-BASIC

LEVEL 2 Source Code Output

More improvements were provided after the step by step tutorial. If you need more features, you might need the LEVEL 2 version. It has the following output:

display-twitter-feed-pro-katy
display-twitter-feed-pro-ninjazhai

See the full list of features in section 15.0 below. It has all the details of these features.

Obtain Access Tokens and Keys

Go to Twitter Apps page.

Click the 'Create New App' button on the upper right corner.

Fill out the form with your information

Go back to the twitter apps page, you should see your new app now

Click your app and go to the "Keys and Access Tokens" tab

twitter-app-keys

There you will see the access tokens and keys you need:

  • Consumer Key (API Key)
  • Consumer Secret (API Secret)
  • Access Token
  • Access Token Secret

Create The index.php File

We will make index.php Bootstrap ready. For those not familiar with the CSS framework Bootstrap, please refer to our step by step tutorial here:

Step by Step Bootstrap Tutorial for Beginners

The index.php file will have 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 Twitter Feed On Website - LEVEL 2 - Live Demo</title>
 
        <!-- Bootstrap CSS -->
    <link href="libs/js/bootstrap/dist/css/bootstrap.css" rel="stylesheet" media="screen">
</head>
<body>
 
<!-- PAGE CONTENT and PHP CODE WILL BE HERE -->
 
<!-- jQuery library -->
<script src="libs/js/jquery.js"></script>
 
<!-- bootstrap JavaScript -->
<script src="libs/js/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="libs/js/bootstrap/docs-assets/js/holder.js"></script>
 
<!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[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>

Put Container Tags, Page Title and HTML

We will have the following code inside the "body" tag of our code in section 4.0

<div class="container">
 
    <div class="col-lg-12">
        <div class="page-header">
            <h1>Display Twitter Feed On Website - LEVEL 1 - Live Demo</h1>
        </div>
    </div>
 
    <div class="col-lg-4">
        <!-- TWITTER USER PROFILE INFORMATION WILL BE HERE -->
    </div> <!-- end <div class="col-lg-4"> -->
 
    <div class="col-lg-8">
        <!-- TWITTER USER FEED WILL BE HERE -->
    </div> <!-- end <div class="col-lg-8"> -->
 
</div> <!-- end <div class="container"> -->

Specify Keys And Variable Values

The following code will be inside the DIV tag with class="col-lg-4".

Access token and keys value were retrieved during our section 3.0 earlier.

<?php
// keys from your app
$oauth_access_token = "change_to_your_oauth_access_token ";
$oauth_access_token_secret = "change_to_your_oauth_access_token_secret ";
$consumer_key = "change_to_your_consumer_key ";
$consumer_secret = "change_to_your_consumer_secret ";
 
// we are going to use "user_timeline"
$twitter_timeline = "user_timeline";
 
// specify number of tweets to be shown and twitter username
// for example, we want to show 20 of Taylor Swift's twitter posts
$request = array(
    'count' => '10',
    'screen_name' => 'taylorswift13'
);
?>

Get OAuth Signature

OAuth is an authentication protocol that allows users to approve application to act on their behalf without sharing their password. More about Twitter OAuth here.

Put the following code below our code on section 6.0

// put oauth values in one oauth array variable
$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_nonce' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_token' => $oauth_access_token,
    'oauth_timestamp' => time(),
    'oauth_version' => '1.0'
);
 
// combine request and oauth in one array
$oauth = array_merge($oauth, $request);
 
// make base string
$baseURI="https://api.twitter.com/1.1/statuses/$twitter_timeline.json";
$method="GET";
$params=$oauth;
 
$r = array();
ksort($params);
foreach($params as $key=>$value){
    $r[] = "$key=" . rawurlencode($value);
}
$base_info = $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
 
// get oauth signature
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

Make The Authorization Request

We can now make request to the Twitter API with the help of $oauth variable and cURL.

Put the follwing code below our code on section 7.0

// make request
// make auth header
$r = 'Authorization: OAuth ';
 
$values = array();
foreach($oauth as $key=>$value){
    $values[] = "$key=\"" . rawurlencode($value) . "\"";
}
$r .= implode(', ', $values);
 
// get auth header
$header = array($r, 'Expect:');
 
// set cURL options
$options = array(
    CURLOPT_HTTPHEADER => $header,
    CURLOPT_HEADER => false,
    CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => true
);

Retrieve Twitter Feeds With User Information

Using the the following code, we can get the data in JSON format. Put it below our code on section 8.0

// retrieve the twitter feed
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
 
// decode json format tweets
$tweets=json_decode($json, true);

Display Twitter User Information

The following code shows how we can display the specified Twitter user's information. Put it below our code on section 9.0

// show user information
echo "<div class='overflow-hidden'>";
 
    // user data
    $profile_photo=str_replace("normal", "400x400", $tweets[0]['user']['profile_image_url_https']);
    $name=$tweets[0]['user']['name'];
    $screen_name=$tweets[0]['user']['screen_name'];
 
    // show profile photo
    echo "<img src='{$profile_photo}' class='img-thumbnail' />";
 
    // show other information about the user
    echo "<div class='text-align-center'>";
        echo "<div><h2>{$name}</h2></div>";
        echo "<div><a href='https://twitter.com/{$screen_name}' target='_blank'>@{$screen_name}</a></div>";
    echo "</div>";
 
    echo "<hr />";
echo "</div>";

Display Twitter User Status Count And Follower Count

Now we will put the following code inside the DIV tag with class="col-lg-8".

<?php
$statuses_count=$tweets[0]['user']['statuses_count'];
$followers_count=$tweets[0]['user']['followers_count'];
 
// show numbers
echo "<div class='overflow-hidden'>";
 
    // show number of tweets
    echo "<div class='float-left margin-right-2em text-align-center'>";
        echo "<div class='color-gray'>Tweets</div>";
        echo "<div class='badge font-size-20px'>" . number_format($statuses_count, 0, '.', ',') . "</div>";
    echo "</div>";
 
    // show number of followers
    echo "<div class='float-left margin-right-2em text-align-center'>";
        echo "<div class='color-gray'>Followers</div>";
        echo "<div class='badge font-size-20px'>" . number_format($followers_count, 0, '.', ',') . "</div>";
    echo "</div>";
 
echo "</div>";
 
echo "<hr />";
?>

Display Twitter Posts / Status Feed

Finally we can now display the user's Twitter posts.

// show tweets
foreach($tweets as $tweet){
 
    // show a tweet
    echo "<div class='overflow-hidden'>";
 
        // show picture
        echo "<div class='tweet-image'>";
            echo "<img src='{$profile_photo}' class='img-thumbnail' />";
        echo "</div>";
 
        // show tweet content
        echo "<div class='tweet-text'>";
 
            // show name and screen name
            echo "<h4 class='margin-top-4px'>";
                echo "<a href='https://twitter.com/{$screen_name}'>{$name}</a> ";
                echo "<span class='color-gray'>@{$screen_name}</span>";
            echo "</h4>";
 
            // show tweet text
            echo "<div class='margin-zero'>";
 
                // get tweet text
                $tweet_text=$tweet['text'];
 
                // make links clickable
                $tweet_text=preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $tweet_text);
 
                // output
                echo $tweet_text;
            echo "</div>";
        echo "</div>";
 
    echo "</div>";
    echo "<hr />";
}

Add Your Custom Styling

The following CSS code is what I used to add a some style on our page. I put it inside the "head" tag, just below the Bootstrap CSS.

<!-- custom CSS -->
<style>
.overflow-hidden{
    overflow:hidden;
}
 
.left-margin-10px{
    margin:0 1em 0 0;
}
 
.margin-right-1em{
    margin-right:1em;
}
 
.margin-right-2em{
    margin-right:2em;
}
 
.text-align-center{
    text-align:center;
}
 
.margin-top-4px{
    margin-top:4px;
}
 
.color-gray{
    color:#999;
}
 
.tweet-image{
    float:left; width:15%;
    margin-right:1em;
}
 
.tweet-image img{
    width:100%;
}
 
.tweet-text{
    float:left; width:80%;
}
 
.margin-zero{
    margin:0;
}
 
.font-size-20px{
    font-size:20px;
}
 
.float-left{
    float:left;
}
</style>

Control Background and Link Colors

You can control or change the background or link colors by going to the design settings section of your twitter account.

Here's how you can go to that page:

  1. Go to twitter.com.
  2. On the upper right corner of the page, click your picture.
  3. Click "Settings" in the dropdown.
  4. On the left side bar, click "Design".

You should see the following page.

display-twitter-feed-pro-design-settings

"Theme Color" is the link color. Changes made here will reflect in your page using the LEVEL 2 source code.

Download The Source Code

Getting The 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, orYES
✔ Income you can get from your website project or business.YES
✔ Precious time you save.YES
✔ Expert advice you can get from me, just in case you have any questions with the code.YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE LEVEL you desire by clicking its the BUY button below.

Download the LEVEL 1 Source Code

FEATURES LEVEL 1
Show Twitter users' profile picture YES
Show Twitter users' name YES
Show Twitter users' username with link YES
Show number of tweets YES
Show exact number of followers YES
Specify number of tweets to display YES
Specify Twitter username where to get tweets YES
Show profile pic in tweets YES
Show profile name in tweets YES
Show profile username in tweets YES
Show original tweets YES
Show retweets YES
Links in tweets are clickable YES
Bootstrap enabled YES
Mobile friendly YES
Download Now

Download LEVEL 2 Source Code

FEATURES LEVEL 2
All features of the LEVEL 1 version YES
Show twitter profile description YES
Show twitter user's website with link YES
Show number of following YES
Show number of favorites YES
Twitter profile mentions in tweets are clickable YES
Show when a tweet was tweeted with "Time ago" format YES
Show profile banner image YES
Apply background color set in design settings YES
Apply link color set in design settings YES
Free email support for 6 months. Yes
Free source code updates. Yes
Download Now

Do you need more reasons to download it?

MORE REASONS TO GET IT
Buy only once, use on unlimited number of websites and Twitter accounts! 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 Twitter feed. 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 Twitter API. YES
Features are constantly improving, and you get it for free. YES
Completely customizable. YES

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

Do You Want a Demo?

If you want a demo to see if this will work with your own Twitter account, please send me a message via email [email protected], or via our official Facebook page!

Please provide your Twitter username on the message, thanks!

Social Media Scripts – LEVEL 3 – PRO PACK

Social Media Scripts - LEVEL 3 - PRO PACK
ITEM Original Cost LEVEL 3 PRO PACK
Display Facebook EVENTS on Website $49.99 YES
Display Facebook PHOTOS on Website $49.99 YES
Display Facebook VIDEOS on Website $49.99 YES
Display Facebook FEED on Website $49.99 YES
Display Instagram FEED On Your Website $49.99 YES
BONUS! The following script does not have LEVEL 3, only LEVEL 2. We will give them to you as bonus.
Display Twitter FEED on Website $29.99 YES
Display Google+ FEED on Website $29.99 YES
BUY TO DOWNLOAD PRO PACK NOW FOR ONLY $309.93 $198
Read more about this package.

What's Next?

Today we have learned how to show a Twitter Feed on your website.

Did you know that you can display Google+ Feed on your website as well?

Let us go to the next tutorial: How To Display Google+ Feed 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 twitter feed on website using PHP!

How to display Instagram Feed on your website using PHP or JavaScript?

Are you looking for a way to display Instagram feed on your website? You probably upload photos, videos, and albums on your Instagram account. And, you have a website as well. Am I right? If that is the case, then it is a good idea to display your Instagram posts on your website!

This is a great way to increase your Instagram followers and engage them in your brand. Today I'm going to show you how to display publicly available Instagram feed on your website using PHP or JavaScript.

3 ways to display Instagram feed on website

I've found out that there are three ways to display Instagram feed on your website. They are the following.

  1. Using the official Instagram API.
  2. Using an alternative API.
  3. Using a website plugin.

I will show you the code how to use those three. Let's dive in!

#1 Using the official Instagram API

On the official documentation, they call this the Instagram Basic Display API. This API allows users to read basic profile information, photos, videos, and albums of the connected account.

  1. Create a Facebook developer account. After you created a developer account, you need to create a Facebook application in the same interface. You can create a Facebook developer account and a Facebook application here.
  2. Configure Instagram's basic display. I think Instagram's documentation is good enough and I don't want to repeat the same instructions here. Follow their getting started guide here.
  3. Get your long-lived access token. By default, Instagram API will give you a short-lived access token which is valid only for 24 hours. If you get your long-lived access token, it will be valid for 60 days. Learn how to get a valid long-lived access token here.

PHP code

Once you got your long-lived access token, use it as the value of the $token variable below. The code below will allow you to display the list of posts

<?php 
// query the user media
$fields = "id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username";
$token = "your_long_lived_user_access_token";
$limit = 10;

$json_feed_url="https://graph.instagram.com/me/media?fields={$fields}&access_token={$token}&limit={$limit}";
$json_feed = @file_get_contents($json_feed_url);
$contents = json_decode($json_feed, true, 512, JSON_BIGINT_AS_STRING);

echo "<div class='ig_feed_container'>";
    foreach($contents["data"] as $post){
        
        $username = isset($post["username"]) ? $post["username"] : "";
        $caption = isset($post["caption"]) ? $post["caption"] : "";
        $media_url = isset($post["media_url"]) ? $post["media_url"] : "";
        $permalink = isset($post["permalink"]) ? $post["permalink"] : "";
        $media_type = isset($post["media_type"]) ? $post["media_type"] : "";
        
        echo "
            <div class='ig_post_container'>
                <div>";

                    if($media_type=="VIDEO"){
                        echo "<video controls style='width:100%; display: block !important;'>
                            <source src='{$media_url}' type='video/mp4'>
                            Your browser does not support the video tag.
                        </video>";
                    }

                    else{
                        echo "<img src='{$media_url}' />";
                    }
                
                echo "</div>
                <div class='ig_post_details'>
                    <div>
                        <strong>@{$username}</strong> {$caption}
                    </div>
                    <div class='ig_view_link'>
                        <a href='{$permalink}' target='_blank'>View on Instagram</a>
                    </div>
                </div>
            </div>
        ";
    }
echo "</div>"
?>

CSS code

Here's the CSS code I used with the code above.

.ig_feed_container{
    width:100%; margin:0 auto; font-family:Arial, Helvetica, sans-serif;
}

.ig_post_container{
    border: 2px solid #f1f1f1; margin-bottom:25px; margin-left:3%; width:20%; height:550px; float:left;
}

.ig_post_container img{
    width:100%;
}

.ig_post_container .ig_post_details{
    padding:15px;
}

.ig_post_container .ig_view_link{
    margin-top:10px;
}

Output

The output will look like the following.

JavaScript Code

I don't recommend using the direct JSON feed URL with JavaScript code. This will easily reveal your long lived access token in the client side or in any user's browser. If you really want to use JavaScript, I suggest you create your own JSON feed on your server first. Then, you use that JSON feed on your JavaScript code.

Another options is to use a JSON feed from an alternative API. This method will never reveal your private or long-lived access token in any browser.

Do you want less work?

If you think following the Instagram documentation is hard and confusing because there are so many steps to follow and their API changes frequently, you can use an alternative API or a website plugin. This will save you a lot of time and remove headaches.

You don't need to deal with a broken data feed because of an Instagram API update. Disclaimer: The suggested products below, AccentAPI and SociableKIT, are developed by my company Codalify Software Development.

#2 Using an alternative API

To get your Instagram account's data feed, you can use an alternative API like AccentAPI.

What are the advantages of using AccentAPI over the official API?

There are data that the official Instagram API will not give you. AccentAPI will give you those missing data. Also, AccentAPI provides an easy-to-use API, tutorials, and human support. See the comparison table below.

FeaturesAccentAPIOfficial Instagram API
Post likes countYESNO
Post comments countYESNO
Profile biographyYESNO
Profile follower countYESNO
Profile following countYESNO
Profile website URLYESNO
Easy-to-use APIYESNO
Easy-to-follow tutorialYESNO
Human chat & email supportYESNO

How to get the link to your Instagram data feed?

  1. You may pay using this link. Pricing is only $2/month, billed annualy.
  2. Once your payment is received, within 24 hours, our AccentAPI team will reply with a link to your data feed.
  3. We offer a 7-days money-back guarantee.

How to display Instagram feed using PHP?

You need to get your own data feed URL from AccentAPI. Once you have that link, you can use it with the following PHP code.

<?php 
// query the user media
$limit = 10;
$json_feed_url="https://app.accentapi.com/api/instagram/feed?username=coolest.buildings&limit={$limit}";
$json_feed = @file_get_contents($json_feed_url);
$contents = json_decode($json_feed, true, 512, JSON_BIGINT_AS_STRING);

echo "<div class='ig_feed_container'>";
    foreach($contents["data"] as $post){
        
        $username = isset($post["username"]) ? $post["username"] : "";
        $caption = isset($post["caption"]) ? $post["caption"] : "";
        $media_url = isset($post["media_url"]) ? $post["media_url"] : "";
        $permalink = isset($post["permalink"]) ? $post["permalink"] : "";
        $media_type = isset($post["media_type"]) ? $post["media_type"] : "";
        
        echo "
            <div class='ig_post_container'>
                <div>";

                    if($media_type=="VIDEO"){
                        echo "<video controls style='width:100%; display: block !important;'>
                            <source src='{$media_url}' type='video/mp4'>
                            Your browser does not support the video tag.
                        </video>";
                    }

                    else{
                        echo "<img src='{$media_url}' />";
                    }
                
                echo "</div>
                <div class='ig_post_details'>
                    <div>
                        <strong>@{$username}</strong> {$caption}
                    </div>
                    <div class='ig_view_link'>
                        <a href='{$permalink}' target='_blank'>View on Instagram</a>
                    </div>
                </div>
            </div>
        ";
    }
echo "</div>"
?>

How to embed Instagram feed using JavaScript?

If you want to use JavaScript, here is the code.

Coming soon!

CSS code

The following is the CSS code I used for both the PHP and JavaScript code above.

.ig_feed_container{
    width:100%; margin:0 auto; font-family:Arial, Helvetica, sans-serif;
}

.ig_post_container{
    border: 2px solid #f1f1f1; margin-bottom:25px; margin-left:3%; width:20%; height:550px; float:left;
}

.ig_post_container img{
    width:100%;
}

.ig_post_container .ig_post_details{
    padding:15px;
}

.ig_post_container .ig_view_link{
    margin-top:10px;
}

#3 Using a website plugin

If you do not want to code, use a "no-code" approach. You can use website plugins like SociableKIT.

What are the advantages of using SociableKIT over the AccentAPI?

SociableKIT have many of AccentAPI's great set features like easy-to-follow video tutorials and human chat and email support, and more. See the comparison table below.

FeaturesSociableKITAccentAPI
No need to learn PHP, JavaScript, or CSS.YESNO
Copy a single line of code and paste it on your website.YESNO
Responsive. Your Instagram feed will look great on mobile, tablet, or desktop.YESNO
Easily change the look & feel using lots of customization options.YESNO
Carousel layout, grid layout, lightbox, pop-up options, and more.YESNO
Use Instagram feed, Facebook posts feed, and more in one place.YESNO

How to use SociableKIT?

The following are the steps that you need to take.

  1. Sign up and log in to SociableKIT.
  2. Create a new solution. Select "Instagram feed" on the drop-down.
  3. Enter your Instagram username and click the Next button.
  4. It will show the customization options like layouts, colors, and more.
  5. Click the Save changes button. On the upper right, click the "Embed on website" button.
  6. Copy the code and paste it on your website.

Click here to see an Instagram feed made with SociableKIT.

SociableKIT offers a 7-days free trial. Their pricing is $4/feed/month if you buy 5 feeds. $2.50/feed/month if you buy 10 or more feeds. $8/month if you buy only one feed.

Thank you!

Thank you for learning from CodeOfaNinja! I hope you learned how to add, display, or embed Instagram feed on your website.

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 Get Facebook App ID and Secret Keys?

After creating a Facebook page where we will pull our data, we have to create an app to get an appId and appSecret keys. Those keys are required to use the Facebook PHP SDK and do our queries like pulling Facebook photos, events, videos, and feeds. Here’s a step by step tutorial on how to get those keys.

How To Get Facebook App ID and Secret Keys?
Facebook developer apps dashboard.

Step 1

Here’s the link where you would start: create a Facebook app. On the pop up, specify your app name (the name of your website or app) and app namespace (used for your Facebook app URL e.g., http://apps.facebook.com/yournamespace)

Creating an app.
Creating an app.

Step 2

You’ll be asked to enter a security code to verify that you’re a human and not a bot or malware that creates random Facebook apps. After entering the text in the box, click the “Continue” button.

A security check.
A security check.

Step 3

Congrats! now you can copy your Facebook appId and appSecret. See the arrows below.

Your Facebook appId and appSecret keys.
Your Facebook appId and appSecret keys.

Step 4

Prepare your App ID and App Secret keys, we’ll use it to get your access token, here’s how:

https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials

Replace YOUR_APP_ID and YOUR_APP_SECRET with your own and run the link on the browser.

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!