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
ITEMOriginal CostLEVEL 3 PRO PACK
Display Facebook EVENTS on Website$49.99YES
Display Facebook PHOTOS on Website$49.99YES
Display Facebook VIDEOS on Website$49.99YES
Display Facebook FEED on Website$49.99YES
Display Instagram FEED On Your Website$49.99YES
BUY TO DOWNLOAD PRO PACK NOW FOR ONLY $249.95 $198

[purchase_link id="8536" text="Download Now" style="button" color="green"]

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!
ITEMOriginal CostLEVEL 3 PRO PACK
Display Twitter FEED on Website$29.99YES
Display Google+ FEED on Website$29.99YES
BUY TO DOWNLOAD PRO PACK NOW FOR ONLY $309.93 $198

[purchase_link id="8536" text="Download Now" style="button" color="green"]

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.

Display Twitter Feed on Website Using PHP

Previously, we learned how to display an Instagram feed on your website using PHP.

Today, this tutorial will help you learn how to display a Twitter feed on your website using PHP. Twitter is a powerful tool for businesses and individuals looking to promote their brands or products.

If you're running a website for your brand, it makes sense to incorporate your Twitter feed into your website. This allows your followers to stay updated with your latest tweets without ever having to leave your site.

However, the standard Twitter widget may not always be the best fit for your website's design. That's why we'll show you how to customize the look and feel of your Twitter feed to match your website's design scheme.

You'll learn how to retrieve tweets, format them, and display them on your website using PHP. So, whether you're a developer or just looking to add this feature to your website, this tutorial is for you.

Don't want to code?

Before we start coding, you might be someone not really interested in coding. Or, you just want a quick solution to adding a Twitter feed to your website.

If that's the case, you need to use a "no code" approach. One way of doing it is to use a website plugin called SociableKIT. It is a free website plugin that allows you to embed your Twitter feed on your website. No coding is required.

Let's go back to coding below.

Source Code Overview

Here’s an overview of what our code does:

  1. It gets a Twitter users' 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 on 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 excellent front-end framework, see our step by step Bootstrap tutorial here.

Final 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

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 sidebar, click "Design."

You should see the following page.

display-twitter-feed-pro-design-settings

"Theme Color" is the link color.

Source code or SociableKIT?

You can choose whether to download our source code or use the SociableKIT Twitter feed widget.

FEATURESCodeSociableKIT
Show Twitter users’ profile pictureβœ”βœ”
Show Twitter users’ nameβœ”βœ”
Show Twitter users’ usernames with linkβœ”βœ”
Show the number of tweetsβœ”βœ”
Show exact number of followersβœ”βœ”
Specify number of tweets to displayβœ”βœ”
Specify Twitter username where to get tweetsβœ”βœ”
Show profile pic in tweetsβœ”βœ”
Show profile name in tweetsβœ”βœ”
Show profile username in tweetsβœ”βœ”
Show original tweetsβœ”βœ”
Show retweetsβœ”βœ”
Links in tweets are clickableβœ”βœ”
Responsive, mobile-friendly layoutβœ”βœ”
No coding required-βœ”
Works with any website builders like WordPress, Squarespace, or Wix-βœ”
Customize colors, font, and more-βœ”
Priority chat and email support-βœ”
Lifetime support and system updates-βœ”
No need to worry about Twitter API updates-βœ”
Use the buttons below. ↓CodeSociableKIT

What's Next?

Congratulations! You completed our series! For now, that is all for our social media API tutorial series.

You may want to explore a different tutorial series. Please select from our web development tutorials.

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

β˜…β˜…β˜…β˜…β˜… β€œWow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

β˜…β˜…β˜…β˜…β˜… β€œThe fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

β˜…β˜…β˜…β˜…β˜… β€œThanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

β˜…β˜…β˜…β˜…β˜… β€œHey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

β˜…β˜…β˜…β˜…β˜… β€œWords can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful Display Twitter Feed on Website Using PHP Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our Display Twitter Feed on Website Using PHP helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about Display Twitter Feed on Website Using PHP

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

Display Instagram Feed on your website using PHP

Previously, we learned how to display Facebook page posts feed on your website using PHP.

Today, our tutorial will explore integrating Instagram into your website by displaying your Instagram feed using PHP. This can be a great way to showcase your content and keep your website visitors engaged with your brand.

Using PHP, we can easily connect to the Instagram API and retrieve your latest posts, allowing them to be displayed on your website. Any new content you upload to Instagram will automatically appear on your website, saving you the hassle of manually updating your website every time you post something new.

Following this tutorial can bring your Instagram content to your website, providing your audience with a seamless browsing experience and keeping them updated with your latest content. So, let's dive in and start displaying your Instagram feed on your website using PHP!

Display Instagram feed on website using PHP

We will use the official Instagram Basic Display API. This API allows users to read basic profile information, photos, videos, and albums of the connected account.

Here are the steps to display the Instagram feed on a website using PHP.

  1. Retrieve long-lived access token.
  2. Use our PHP code to display your Instagram feed.
  3. Use our CSS code to make the display look good.
  4. View our output.

Retrieve your long-lived access token

The long-lived access token is like a key that you will use to retrieve your Instagram photos and videos programmatically. You will use this token on our PHP code later.

  1. Create a Facebook developer account. Create your Facebook developer account here. Then, you also need to create a Facebook application here.
  2. Configure Instagram's basic display API. Instagram's documentation is good enough, and I don't want to repeat the exact same instructions here. Follow the guide here.
  3. Get your long-lived access token. By default, Instagram API will give you a short-lived access token that 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.

Use our PHP code to display your Instagram feed

Once you get 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>"
?>

Use our CSS code to make the display look good

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

View our output

The output will look like the following.

We will also cover using a website plugin to achieve the same output. This is best for people who do not want to code. Continue reading below.

Display Instagram feed using a website plugin

If you do not want to code, use a "no-code" approach. You can use website plugins like SociableKIT. Follow this tutorial: embed your Instagram feed on your website. You can use its free plan if you do not need the premium features.

Step-by-step guide

Follow the steps below to display your Instagram feed using a website plugin.

  1. Sign up for SociableKIT. You will be logged in automatically after you enter your email address.
  2. Create a new solution. Select "Instagram feed" on the drop-down. Enter your Instagram username.
  3. Click the Next button. It will show the customization options like layouts, colors, and more. Click the Save changes button.
  4. Copy embed code. On the upper right, click the "Embed on website" button. Copy the embed code.
  5. Paste on your website. Create a new page or edit an existing page on your website. Paste the embed code where you want the Instagram feed to appear.

Using SociableKIT, you can also display Instagram reels, Instagram hashtag feed, Instagram stories, and more on your website.

Output

Your Instagram feed using SociableKIT can look like the following.

Example Instagram feed #1
Example Instagram feed #2

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 a Twitter feed on your website?

Let us go to the next tutorial: How to display a Twitter feed on website?

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

β˜…β˜…β˜…β˜…β˜… β€œWow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

β˜…β˜…β˜…β˜…β˜… β€œThe fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

β˜…β˜…β˜…β˜…β˜… β€œThanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

β˜…β˜…β˜…β˜…β˜… β€œHey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

β˜…β˜…β˜…β˜…β˜… β€œWords can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful Display Instagram Feed on your website using PHP Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our Display Instagram Feed on your website using PHP helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about Display Instagram Feed on your website using PHP

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

Display Facebook Page Videos On Website Using PHP

Previously, we learned how to display Facebook page photo albums on your website.

Today, our tutorial will explore integrating Facebook page videos onto a website using PHP. With this solution, website visitors can easily access the videos you've invested time in creating, editing, and managing on your Facebook page.

Say goodbye to manually uploading videos to both Facebook and your website. Implement our code and have your Facebook videos automatically displayed on your website for your audience to enjoy.

This is a great way to increase engagement on your website and encourage your audience to follow your Facebook page.

Overview

This code will get the list of videos from your Facebook page 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!

We will display these videos on a webpage made in PHP. We will use a user interface powered by Bootstrap. See our step-by-step Bootstrap tutorial here if you’re not yet familiar with this excellent front-end framework.

Don’t want to code?

Before we continue coding, if you realize you do not want to code and need more features, you can use a website plugin called SociableKIT. It is the best no-code tool for the job.

You can easily customize the look and feel of your Facebook page video feed and embed it on your website in 3 minutes. The videos feed on your website will update automatically.

Follow this tutorial: Embed Facebook page videos on website. You can also embed Facebook page live streams and Facebook page playlist videos. There’s a free plan that you can use if you don’t need the premium features of SociableKIT.

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:

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';
}

Source code or SociableKIT?

You can choose whether to download our source code or use the SociableKIT Facebook page videos widget.

FEATURESCodeSociableKIT
Upload videos on your Facebook page and automatically display them on your website.βœ”βœ”
Save time figuring out and coding these features on your website.βœ”βœ”
Display the list of videos from your Facebook page.βœ”βœ”
Display video title. If none, display the video number.βœ”βœ”
Display video description.βœ”βœ”
Post date with β€œtime ago” format.βœ”βœ”
Display the Facebook page name (with a link) for each video. (opens in new tab)βœ”βœ”
Responsive layout. (excellent for mobile devices)βœ”βœ”
No coding required-βœ”
Works with any website builders like WordPress, Squarespace, or Wix-βœ”
Customize colors, font, and more-βœ”
Event details with a map can be shown in a popup-βœ”
Priority chat and email support-βœ”
Lifetime support and system updates-βœ”
No need to worry about Facebook API updates-βœ”
Use the buttons below. ↓CodeSociableKIT

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 a Facebook page posts feed on your website?

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

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

β˜…β˜…β˜…β˜…β˜… β€œWow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

β˜…β˜…β˜…β˜…β˜… β€œThe fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

β˜…β˜…β˜…β˜…β˜… β€œThanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

β˜…β˜…β˜…β˜…β˜… β€œHey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

β˜…β˜…β˜…β˜…β˜… β€œWords can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful Display Facebook Page Videos On Website Using PHP Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our Display Facebook Page Videos On Website Using PHP helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about Display Facebook Page Videos On Website Using PHP

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

Display Facebook page posts feed on website using PHP

Previously, we learned how to display Facebook page videos on your website using PHP.

Today, in this tutorial, we will show you how to display Facebook page posts on your website using PHP. Posts from your Facebook page are essential to keep your audience informed, engaged, and updated with your latest content.

However, if you're not showing those posts to your website visitors, you miss out on a valuable opportunity to connect with them.

Our code in this tutorial will allow you to automatically display your Facebook page posts on your website using PHP. The integration process is straightforward, and once it's done, you can create and edit your posts on Facebook, and any changes will also be reflected on your website.

This will save you time and effort, as you won't need to manually update your website whenever you create a new post.

Overview

Our code for today will get any posts like videos, statuses, or pictures from your Facebook page using Facebook Graph API. We will beautifully display these posts or contents on a webpage (assuming it is your website) with Bootstrap.

See our step-by-step Bootstrap tutorial if you’re not yet familiar with this awesome front-end framework. It is also responsive, so it’s one advantage for mobile devices.

Don't want to code?

Before we continue coding, if you realize you do not want to code and need more features, you can use a website plugin called SociableKIT. It is the best no-code tool for the job.

You can easily customize the look and feel of your Facebook feed and embed it on your website in 3 minutes. The posts feed on your website will update automatically.

Follow this tutorial: Embed Facebook page posts feed on website. You can also embed other feeds, such as Facebook page events, photos, videos, and more. There’s a free plan that you can use if you don’t need the premium features of SociableKIT.

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

Code Output

It is essential to know where we are going. Once we finish 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>"; 

Source code or SociableKIT?

You can choose whether to download our source code or use the SociableKIT Facebook page events widget.

FEATURESCodeSociableKIT
Do it once: post on your Facebook page and automatically show it on your websiteβœ”βœ”
Save time studying and coding these features on your websiteβœ”βœ”
Automatically show the type of post. It can be status, link, video, etc.βœ”βœ”
Posts are linked to your Facebook page. Engage your visitors to your Facebook page.βœ”βœ”
The status post will have a β€œView On Facebook” linkβœ”βœ”
Posts will show the link thumbnail, title, and descriptionβœ”βœ”
Shows posted photoβœ”βœ”
Display the number of likesβœ”βœ”
Display the number of commentsβœ”βœ”
Responsive layout (great for mobile devices!)βœ”βœ”
Show β€œtime ago” of postsβœ”βœ”
Show like and comment iconsβœ”βœ”
No coding required-βœ”
Works with any website builders like WordPress, Squarespace, or Wix-βœ”
Customize colors, font, and more-βœ”
Priority chat and email support-βœ”
Lifetime support and system updates-βœ”
No need to worry about Facebook API updates-βœ”
Use the buttons below. ↓CodeSociableKIT

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 an Instagram feed on website using PHP?

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

β˜…β˜…β˜…β˜…β˜… β€œWow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

β˜…β˜…β˜…β˜…β˜… β€œThe fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

β˜…β˜…β˜…β˜…β˜… β€œThanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

β˜…β˜…β˜…β˜…β˜… β€œHey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

β˜…β˜…β˜…β˜…β˜… β€œWords can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful Display Facebook page posts feed on website using PHP Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our Display Facebook page posts feed on website using PHP helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about Display Facebook page posts feed on website using PHP

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

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.

Display Facebook page events on website using PHP

Welcome to the start of our Social Media API Tutorial Series! We will start with this tutorial about how to display Facebook page events on your website using PHP.

In today's digital age, social media plays a crucial role in connecting businesses with their customers. As a business owner, you understand the importance of keeping your website up-to-date with the latest information about your company, including upcoming events.

However, manually updating your website with events from your Facebook page can be time-consuming and tedious.

In this tutorial, we will explore a solution to this problem by demonstrating how to use the Facebook API and PHP to automatically display your Facebook page events on your website.

With the code provided, you will be able to seamlessly integrate your Facebook events into your website, ensuring that your audience is always up-to-date with the latest happenings at your business.

Say goodbye to manual updates and hello to a streamlined and efficient way of sharing your events with your fans, audience, and customers.

Overview

This code will get the list of events from your Facebook page. It will show 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!

We will display these event data on a webpage, assuming it is a website made with PHP. We will use a user interface powered by Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step-by-step Bootstrap tutorial here.

Don't want to code?

Before we continue coding, if you later realize you do not want to code and need more features, you can use a website plugin called SociableKIT. It is the best no-code tool for the job.

You can easily customize the look and feel of your Facebook page events feed and embed it on your website in 3 minutes. The events feed on your website will update automatically.

Follow this tutorial: Embed Facebook page events on website. You can also use the Facebook group events solution if you use Facebook groups. There's a free plan that you can use if you don't need the premium features of SociableKIT.

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

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 an 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 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>";
?>

Source code or SociableKIT?

You can choose whether to download our source code or use the SociableKIT Facebook page events widget.

FEATURESCodeSociableKIT
Manage events for your Facebook Page and website onceβœ”βœ”
Save time figuring out and coding these features on your websiteβœ”βœ”
Display a list of upcoming eventsβœ”βœ”
Display event cover photo (profile picture if none)βœ”βœ”
Display event titleβœ”βœ”
Display event date and timeβœ”βœ”
Display event locationβœ”βœ”
Display event descriptionβœ”βœ”
Link to actual Facebook page event (opens in new tab)βœ”βœ”
Responsive layout (great for mobile devices)βœ”βœ”
No coding required-βœ”
Works with any website builders like WordPress, Squarespace, or Wix-βœ”
Customize colors, font, and more-βœ”
Event details with a map can be shown in a popup-βœ”
Priority chat and email support-βœ”
Lifetime support and system updates-βœ”
No need to worry about Facebook API updates-βœ”
Use the buttons below. ↓CodeSociableKIT

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?

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

β˜…β˜…β˜…β˜…β˜… β€œWow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

β˜…β˜…β˜…β˜…β˜… β€œThe fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

β˜…β˜…β˜…β˜…β˜… β€œThanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

β˜…β˜…β˜…β˜…β˜… β€œHey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

β˜…β˜…β˜…β˜…β˜… β€œWords can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful Display Facebook page events on website using PHP Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our Display Facebook page events on website using PHP helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about Display Facebook page events on website using PHP

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

How to display Facebook page photo albums on website using PHP?

Previously, we learned how to display Facebook page events on your website using PHP.

This tutorial will cover the steps to display Facebook page photo albums on your website using PHP. We'll show you how to easily integrate your Facebook page's photo albums into your website so your audience can view them without having to navigate away from your site.

By the end of this tutorial, you'll have a seamless way to showcase your Facebook photo albums to your website visitors, keeping them engaged and up-to-date with your latest content.

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 an awesome image pop-up presentation. This extension is fully responsive and touch-enabled. Good for every mobile device!

Don't want to code?

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

You can easily customize the look and feel of your Facebook page photo albums and embed them on your website within a few clicks. Following this tutorial: Embed Facebook page photo albums on website. There's also an option to embed only one photo album on Facebook.

There's a free plan that you can use if you don't need the premium features of SociableKIT. But if you like coding, continue with our tutorial below!

Benefits

Use this code to enjoy the following benefits.

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

Get your page access token

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="https://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>";
 
}

Source code or SociableKIT?

You can choose whether to download our source code or use SociableKIT's Facebook page photo albums widget.

FEATURESCodeSociableKIT
Manage photos on your Facebook page and website only onceβœ”βœ”
Save time figuring out and coding these features on your websiteβœ”βœ”
Display a list of photo albumsβœ”βœ”
Display album coverβœ”βœ”
Display album descriptionβœ”βœ”
Display the number of photos inside an albumβœ”βœ”
Link to an actual Facebook album page (opens in new tab)βœ”βœ”
Clicking a photo album will show a list of photosβœ”βœ”
Each photo is in a square thumbnailβœ”βœ”
Clicking a photo will pop a lightboxβœ”βœ”
Navigate photos using the lightbox’s Next and Prev buttonsβœ”βœ”
Responsive photo albums pageβœ”βœ”
Responsive photos pageβœ”βœ”
Responsive lightbox pop-up windowβœ”βœ”
Touch-enabled lightbox gallery (great for smartphone and tablet devices)βœ”βœ”
Bootstrap UI enabledβœ”βœ”
Can show more than 25 photo albumsβœ”βœ”
Can show more than 25 photos inside an albumβœ”βœ”
The photo album cover automatically cropped to a specific sizeβœ”βœ”
No need to make each photo album cover the same sizeβœ”βœ”
Font awesome iconsβœ”βœ”
Share buttons on the photos pageβœ”βœ”
No coding required-βœ”
Works with any website builders like WordPress, Squarespace, or Wix-βœ”
Customize colors, font, layout, texts, and more-βœ”
Priority chat and email support-βœ”
Lifetime support and system updates-βœ”
No need to worry about Facebook API updates-βœ”

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?

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

β˜…β˜…β˜…β˜…β˜… β€œWow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

β˜…β˜…β˜…β˜…β˜… β€œThe fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

β˜…β˜…β˜…β˜…β˜… β€œThanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

β˜…β˜…β˜…β˜…β˜… β€œHey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

β˜…β˜…β˜…β˜…β˜… β€œWords can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful How to display Facebook page photo albums on website using PHP? Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our How to display Facebook page photo albums on website using PHP? helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about How to display Facebook page photo albums on website using PHP?

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!