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?
u
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.

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

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 builder or CMS you use.We have tried it in Squarespace, Wix, Weebly, Shopify and WordPress. Here’s the official tutorial on how to use our plugin: How To Embed Customized Facebook Events On Your Website Without Coding?

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 Social Media Scripts – LEVEL 3 – PRO PACK
21.0 DSM Facebook Events WordPress Plugin PRO
22.0 DSM Facebook Events Website Plugin
23.0 Do You Want a Demo?

24.0 What’s Next?
25.0 Related Source Codes
26.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

FEATURESLEVEL 1
Manage events for your Facebook Page and website onceYes
Save time figuring out and coding these features on your websiteYes
Display list of all eventsYes
Display list of upcoming eventsYes
Display list of past eventsYes
Display event cover photo (profile picture if none)Yes
Display event titleYes
Display event date and timeYes
Display event locationYes
Display event descriptionYes
Link to actual Facebook event (opens in new tab)Yes
Bootstrap UI enabledYes
Responsive layout (great for mobile devices)Yes
Free source code updates for 6 monthsYes
Fast and friendly email support for 6 monthsYes
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

FEATURESLEVEL 2
All features of the LEVEL 1 source codeYes
Load more events automatically when scrollingYes
Display number of people attending the eventYes
Link to profiles of some people attending the eventYes
Display event in Google map with pointerYes
Calendar viewYes
Responsive calendar view (great for mobile devices)Yes
Next Month button navigationYes
Prev Month button navigationYes
Highlight calendar cells with eventsYes
Calendar cells with events will pop up event info when clickedYes
“See more” and “See less” toggle in event descriptionYes
Share event buttons (Facebook, Twitter, Google)Yes
Font awesome iconsYes
Link to Google Maps to view full mapYes
Tickets LinkYes
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

FEATURESLEVEL 3
Almost all features of the LEVEL 2 source codeYes
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 up to 10 websites and Facebook pages!Yes
No different kind of licenses.Yes
No monthly or any recurring fees.Yes
No need to rely on another website to render Facebook 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!

20.0 Social Media Scripts – LEVEL 3 – PRO PACK

social media script level 3 pro pack

Download the Social Media Scripts – LEVEL 3 – PRO PACK source codes and save $110+ → click the green button below to learn more.

The PRO PACK includes all our LEVEL 3 social media scripts like Facebook events scripts, Facebook photos, Facebook videos, Facebook timeline, Instagram feed and more!

21.0 DSM Facebook Events WordPress Plugin PRO

I decided to make a WordPress plugin version of this code because many people are requesting it. So here’s what I came up with: How to Show Facebook Events on WordPress Site?

22.0 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 Customized Facebook Events On Your Website Without Coding?

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.

23.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!

24.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?

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

26.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 Become a true Ninja!

  • Subscribe to social media scripts tutorial news and updates.
  • Be updated about what works and what does not work on social media APIs.
  • Be notified for any related social media API updates.
100% Privacy. We will never spam you!

#3 Thank You!

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