How To Display Facebook EVENTS on Website? Step By Step Guide!

display-facebook-events-on-website

Do you have an event manager on your website? Do you create events on your Facebook page?

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

What if there’s a way to create an event ONCE, and then let it appear both on your Website and Facebook page? Will you be happy saving your precious time?

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

Today we’re gonna talk about how to display publicly available Facebook Page EVENTS on your website.

This one is great if you want your Facebook events to be shown in your website in a synchronized way.

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

IMPORTANT UPDATE: A lot of people requested a website plugin version of this code. Now it is available. Now you do not have to code anything. You won’t have to worry about Facebook graph API updates anymore. It works no matter what website platform you use.

We have tried it in WordPress, Squarespace, Wix and more. Here’s the official tutorial on how to use our plugin: How To Embed, Show or Display Customized Facebook Events On Your Website?

The advantages and risks of this is almost the same with what I discussed in my first post  related to this one.

Today post will include the following contents:

1.0 Source Code Overview
2.0 Final Code Output

3.0 Create An App On Facebook Developers Website
4.0 Create An index.php File And Put A Page Title
5.0 Make index.php Bootstrap Ready
6.0 Add A Page Header
7.0 Get Your Facebook Page ID
8.0 Specify The “Since” and “Until” Dates To Get The Events
9.0 Get Your App’s Access Token
10.0 Prepare The FB Graph API Link
11.0 Decode The JSON String
12.0 Prepare The Table And Loop
13.0 Put The Event Values In Variables
14.0 Put The Values In TD Tags

15.0 How To Display Past Events?
16.0 How To Display Upcoming Events?
17.0 How Do I Change The Order Of The Events?

18.0 What People Say About This Code?
18.1 From Blog Comments
18.2 From Emails
18.3 From Facebook Messages

19.0 Download the Complete Source Code
20.0 Use The DSM Facebook Events Website Plugin
21.0 Do You Want a Demo?

22.0 What’s Next?
23.0 Related Source Codes
24.0 Some Notes

1.0 Source Code Overview

Here’s an overview of what our code does:

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

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

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

2.0 Display Facebook Events On Website – Output

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

2.1 LEVEL 1 Source Code – Output Preview

2.2 LEVEL 2 Source Code – Output Preview

2.3 LEVEL 3 Source Code Output

The demo above shows Celebrity Theatre’s gigs from his Facebook event link: https://www.facebook.com/CelebrityTheatre/events

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

Up next will be the step by step programming – fun part! Enjoy!

3.0 Create An App On Facebook Developers Website

You can follow our tutorial on how to create an app on Facebook developers website. Take note of the App ID and App Secret keys.

4.0 Create An index.php File And Put A Page Title

We will declare a page title via PHP this way:

<?php $page_title ="Display Facebook Page Events on Website"; ?>

5.0 Make index.php Bootstrap Ready

Add the following code on our index.php to make it Bootstrap ready. Bootstrap allows us to have a decent looking user interface, if you’re not familiar with it, please visit our Bootstrap step by step guide.

Notice that we put <?php echo $page_title; ?> inside the title tag. We have to make use of our section 4.0 above.

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

<!-- events will be here -->

</div>


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

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

</body>
</html>

6.0 Add A Page Header

Again, we have to make use of our section 4.0 above, the Bootstrap way.


<div class="page-header">

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

</div>

7.0 Get Your Facebook Page ID

The testing Facebook page we used here is https://www.facebook.com/NinjaDummyPage, and its Facebook page id is 221167777906963. How did I get that ID? Just use this tool I made for you.

Once you get your Facebook page ID, put this code below the section 4.0 code, just replace the ID with your own.

<?php $fb_page_id = "221167777906963"; ?>

8.0 Specify The “Since” and “Until” Dates To Get The Events

Specifying the ‘since’ and ‘until’ dates below will get all the Facebook events 2 years before and 2 years after the current year in your page.

$year_range = 2;

// automatically adjust date range
// human readable years
$since_date = date('Y-01-01', strtotime('-' . $year_range . ' years'));
$until_date = date('Y-01-01', strtotime('+' . $year_range . ' years'));

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

// or you can set a fix date range:
// $since_unix_timestamp = strtotime("2012-01-08");
// $until_unix_timestamp = strtotime("2018-06-28");

9.0 Get Your App’s Access Token

Before you can get any data from the FB graph API, you need an access token. Prepare your App ID and App Secret keys from section 3.0 above, 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.

Put the value you see inside the $access_token variable. Change YOUR_ACCESS_TOKEN below.

$access_token = "YOUR_ACCESS_TOKEN";

10.0 Prepare The FB Graph API Link

This link is where the JSON string will be retrieved. We get the JSON contents via PHP’s file_get_contents() function.

$fields="id,name,description,place,timezone,start_time,cover";

$json_link = "https://graph.facebook.com/{$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);

11.0 Decode The JSON String

We have to decode the JSON string using the json_decode() function and convert it to an associative array by setting the second parameter to true. We also used JSON_BIGINT_AS_STRING parameter since Facebook uses large integers (eid) and we don’t want PHP to simplify the value.

$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);

12.0 Prepare The Table And Loop

This time we are actually retrieving the events from Facebook. We are going to put it in an HTML table powered by Bootstrap, that’s why we have to classes below.

echo "
<table class='table table-hover table-responsive table-bordered'>";

    // count the number of events
    $event_count = count($obj['data']);

    for($x=0; $x<$event_count; $x++){
        // facebook events will be here
    }
echo"</table>";

13.0 Put The Event Values In Variables

Inside our for loop, we are going to put the event values in variables.


// set timezone
date_default_timezone_set($obj['data'][$x]['timezone']);

$start_date = date( 'l, F d, Y', strtotime($obj['data'][$x]['start_time']));
$start_time = date('g:i a', strtotime($obj['data'][$x]['start_time']));
 
$pic_big = isset($obj['data'][$x]['cover']['source']) ? $obj['data'][$x]['cover']['source'] : "https://graph.facebook.com/{$fb_page_id}/picture?type=large";

$eid = $obj['data'][$x]['id'];
$name = $obj['data'][$x]['name'];
$description = isset($obj['data'][$x]['description']) ? $obj['data'][$x]['description'] : "";

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

$location="";

if($place_name && $city && $country && $zip){
	$location="{$place_name}, {$city}, {$country}, {$zip}";
}else{
	$location="Location not set or event data is too old.";
}

14.0 Put The Values In TD Tags

This is how we put values in the HTML table for our output. Put this code inside the for loop, after the code in section 12.0.

echo "<tr>";
	echo "<td rowspan='6' style='width:20em;'>";
		echo "<img src='{$pic_big}' width='200px' />";
	echo "</td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td style='width:15em;'>What:</td>";
	echo "<td><b>{$name}</b></td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td>When:</td>";
	echo "<td>{$start_date} at {$start_time}</td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td>Where:</td>";
	echo "<td>{$location}</td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td>Description:</td>";
	echo "<td>{$description}</td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td>Facebook Link:</td>";
	echo "<td>";
		echo "<a href='https://www.facebook.com/events/{$eid}/' target='_blank'>View on Facebook</a>";
	echo "</td>";
echo "</tr>";

15.0 How To Display Past Events?

To display all past event, you just have to set the ‘since date’ to the past x years (set in $year_range variable), and the ‘until date’ to yesterday.

// get events for the past x years
$year_range = 1;

// automatically adjust date range
// human readable years
$since_date = date('Y-01-01', strtotime('-' . $year_range . ' years'));
$until_date = date('Y-m-d', strtotime('-1 day'));

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

Important Notes:

In the Facebook Page events tab, there are two link buttons: “Upcoming Events” and “Past Events”, sometimes, when you click the “Past Events” link, it doesn’t show the past events you created. But it shows on our script which means it’s in the Facebook events database. I think this is a Facebook bug that they have to address.

I also recommend to set the “year range” to “1” because sometimes, Facebook returns the wrong data, like when you have a long date range or when you have a huge list of events within a long date range.

16.0 How To Display Upcoming Events?

To display the events today and in the future, you just have to set the ‘since date’ to today and the ‘until date’ to the future date (affected by the $year_range variable)

// get events for the next x years
$year_range = 1;

// automatically adjust date range
// human readable years
$since_date = date('Y-m-d');
$until_date = date('Y-12-31', strtotime('+' . $year_range . ' years'));

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

17.0 How Do I Change The Order Of The Events?

Unfortunately, Facebook API does not give us the ability to sort the order of events, but I made a workaround for it. Use the following before the ‘for loop’ code:

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");

The only disadvantage is that, it will only sort the currently loaded JSON content.

18.0 What People Say About This Code?

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

18.1 From Blog Comments

★★★★★ “Hi Mike, amazing tutorial.” ~ simonerama

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

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

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

★★★★★ “Hi it’s working great :)” ~ Sebastian

18.2 From Emails

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

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

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

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

18.3 From Facebook Messages

★★★★★ “Hey Mate, code’s a lifesaver (and time saver!)” ~ Andrew

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

★★★★★ “Mike it’s great and simple! I like! Thank you!” ~ Jasmin

★★★★★ “You’re a life saver, thanks so much.” ~ Brendon

19.0 Download the Complete Source Code

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

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

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

19.1 Download the LEVEL 1 Source Code

FEATURES LEVEL 1
Manage events for your Facebook Page and website once Yes
Save time figuring out and coding these features on your website Yes
Display list of all events Yes
Display list of upcoming events Yes
Display list of past events Yes
Display event cover photo (profile picture if none) Yes
Display event title Yes
Display event date and time Yes
Display event location Yes
Display event description Yes
Link to actual Facebook event (opens in new tab) Yes
Bootstrap UI enabled Yes
Responsive layout (great for mobile devices) Yes
Free source code updates for 6 months Yes
Fast and friendly email support for 6 months Yes
LEVEL 1: BUY AND DOWNLOAD NOW USING
* You can use your debit or credit card with PayPal.

19.2 Download the LEVEL 2 Source Code

FEATURES LEVEL 2
All features of the LEVEL 1 source code Yes
Load more events automatically when scrolling Yes
Display number of people attending the event Yes
Link to profiles of some people attending the event Yes
Display event in Google map with pointer Yes
Calendar view Yes
Responsive calendar view (great for mobile devices) Yes
Next Month button navigation Yes
Prev Month button navigation Yes
Highlight calendar cells with events Yes
Calendar cells with events will pop up event info when clicked Yes
“See more” and “See less” toggle in event description Yes
Share event buttons (Facebook, Twitter, Google) Yes
Font awesome icons Yes
Link to Google Maps to view full map Yes
Tickets Link Yes
LEVEL 2: BUY AND DOWNLOAD NOW USING
* You can use your debit or credit card with PayPal.

19.3 Download The LEVEL 3 Source Code

FEATURES LEVEL 3
Almost all features of the LEVEL 2 source code Yes
Object oriented programming. Yes
New compact and responsive design. [see demo] Yes
Show event details on a modal / pop up. Yes
Show event details without refresh. Yes
Specify date range by number of months. Yes
LEVEL 3: BUY AND DOWNLOAD NOW USING
* You can use your debit or credit card with PayPal.

Here in the LEVEL 3 source code, we removed the “infinite scroll” feature. The reason is simple:

Facebook graph API does not allow us to sort the events from the nearest date to farthest, for example an event on April 3rd must be shown first before the event on June 15th.

It always return the farthest date first then the nearest, for example, currently, it will show the event on June 15th first before the April 3rd.

We think the type of sorting above is not useful for showing upcoming events.

Do you need more reasons to download it?

MORE REASONS TO GET IT
Buy only once, use on unlimited number of websites and Facebook pages! Yes
No different kind of licenses. Yes
No monthly or any recurring fees. Yes
No need to rely on another website to render Facebook events. Yes
No need for codes from other websites. Yes
You can learn more how to code, I love teaching and can give you free tips! Yes
Familiarize yourself with the Facebook Graph API. Yes
Tutorial above is always free. Yes
Completely customizable. Yes

Thank you for supporting our projects!

19.4 Download The Social Media Script – LEVEL 2 – PRO PACK

This pack contains all the 7 social media scripts (LEVEL 2) we have. If you will buy them all one by one, it will cost you $210. But, if you will download this pack, it will be $119 only. You just saved $90!

Social Media Scripts - LEVEL 2 PRO PACK
ITEM VIEW LEVEL 2 PRO PACK
Display Facebook EVENTS on Website YES
Display Facebook PHOTOS on Website YES
Display Facebook VIDEOS on Website YES
Display Facebook TIMELINE on Website YES
Display Instagram FEED On Your Website YES
Display Twitter FEED on Website YES
Display Google+ FEED on Website YES
BUY PRO PACK NOW USING
* You can use your debit or credit card with PayPal.

20.0 Use The DSM Facebook Events Website Plugin

You demanded it, we built it. A lot of people requested a website plugin version of this code. Now it is available. Our website plugin has all the features of our LEVEL 3 source code above, plus more!

It works no matter what website platform you use. We have tried it in WordPress, Squarespace, Wix and more. Here’s the official tutorial on how to use our plugin: How To Embed, Show or Display Customized Facebook Events On Your Website?

Our website plugin is super easy to use and is fully customizable – without any need for coding. You can customize any details like the font, backgrounds, colors, and what to show or hide!

To learn more, please go to the plugin’s official tutorial page. Click the green button below.

21.0 Do You Want a Demo?

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

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

22.0 What’s Next?

Today we have learned how to show your Facebook 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 PHOTOS on Website?

23.0 Related Source Codes

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

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

24.0 Some Notes

#1 Found An Issue?

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

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

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

#2 Need Web Hosting?

Do you need a web host for your PHP projects? This will enable your project to be accessible online.

I can provide one for you for a very affordable price of $3 per month. I will give you access to FTP, PhpMyAdmin and other things you need for development.

Send me a message on our official Facebook page, or via my email mike@codeofaninja.com, we will set up your server and URL!

#3 Need A Coder?

If you don’t like coding but wanna make it work on your website, even with any customization, don’t worry, I'll help you with the best I can!

Just contact me by sending a message on our official Facebook page, or via my email mike@codeofaninja.com, I’m more than willing to help you!

#4 Web Resources

If you need Bootstrap website themes, Bootstrap dashboard theme, my highly recommended books and other very useful resource for developers, please visit this page.

If you love high quality, good looking, educational and inspirational pictures about programming and tech industry, you should follow us on Instagram.

#5 Thank You!

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