How To Display Facebook Page Events on Website using PHP?

Before we start coding, you might be someone NOT interested in coding. If that's the case, you should use a website plugin like SociableKIT. Watch the following video.

Need to embed a single Facebook page event on your website? Watch this tutorial.

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

Let's code!

Do you 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 page 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.

Today post will include the following contents:

1.0 Source code overview
2.0 Final code output

3.0 Create index.php file with a page title
4.0 Make index.php bootstrap ready
5.0 Add a page header
6.0 Get your Facebook page ID
7.0 Specify the "since" and "until" dates
8.0 Get your page access token
9.0 Prepare the FB graph API link
10.0 Decode the JSON string
11.0 Prepare the table and loop
12.0 Put the event values in variables
13.0 Put the values in TD tags

14.0 How to display past events?
15.0 How to display upcoming events?
16.0 How to change the order of events?

17.0 What people say about this code?
17.1 From blog comments
17.2 From emails
17.3 From Facebook messages

18.0 Download the complete source code
19.0 SociableKIT Facebook Page Events Website Plugin
20.0 Do you want a demo?

21.0 What's next?
22.0 Related source codes
23.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 Page Events On Website - Output

We have to know where we are going. If we completed the tutorial below, we will achieve the following LEVEL 1 source code output.

2.1 BASIC Source Code - Output Preview


2.2 PRO Source Code - Output Preview


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

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

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

Create a new index.php file and place the following code.

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

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

In the code below, you will see that we put <?php echo $page_title; ?> inside the title tag. That's how we used the $page_title variable from the previous section.

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

	<!-- Bootstrap CSS -->
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">

</head>
<body>
	

<div class="container">

<!-- events will be here -->

</div>

<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>
</html>

5.0 Add A Page Header

Replace <!-- events will be here --> comment above with the following code.


<div class="page-header">

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

</div>

6.0 Get Your Facebook Page ID

On the live demo, the testing Facebook page we used was https://www.facebook.com/postedbydsm, and its Facebook page id is postedbydsm.

How did I get that ID? Just use this tool I made for you.

You must use your Facebook page ID. Once you get your Facebook page ID, place the following code after the previous section's code.

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

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

Specifying the 'since' and 'until' dates below will get all the Facebook page 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");

// page access token
$access_token = "YOUR_ACCESS_TOKEN";

8.0 Get your page access token

Before you can get events 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 of the previous section with your page access token.

9.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/v3.0/{$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);

10.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);

11.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 page events will be here
    }
echo "</table>";

12.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/v2.7/{$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.";
}

13.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>";

14.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);

15.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);

16.0 How to 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.

17.0 What People Say About This Code?

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

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

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

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

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

18.1 Download the BASIC Source Code

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

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

18.2 Download the PRO Source Code

FEATURES PRO
All features of the BASIC source code Yes
Display number of 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
Font awesome icons Yes
Link to Google Maps to view full map Yes
Tickets Link Yes
Object oriented programming. Yes
New compact and responsive design. Yes
Show event details on a modal / pop up. Yes
Show event details without refresh. Yes
Specify date range (in code) by number of months. Yes
Download Now

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

Do you need more reasons to download it?

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

Thank you for supporting our projects!

19.0 SociableKIT Facebook Page Events Website Plugin

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

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

21.0 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 PHOTOS on Website?

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

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

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

#3 Thank You!

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