How to display Facebook page events on website using PHP?

display-facebook-events-on-website

Do you want to learn how to display Facebook page events on your website? What if there’s a way to create an event once, and then let it appear both on your website and Facebook page?

Today we’re gonna talk about how to display publicly available Facebook Page events on your website. This one is great if you want your Facebook page events to be shown on your website in a synchronized way.

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

Don’t want to code?

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

You can easily customize the look and feel of your Facebook page posts feed and embed it on your website within a few clicks. See a tutorial here.

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

Overview

Here’s an overview of what our code does:

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

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

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

Final output

We have to know where we are going. If we completed the tutorial below, we will achieve the following output in the video below.

Create the index page

Create index.php file

This page is what will be loaded on the browser. Create index.php file. Put the following basic HTML code.

<!DOCTYPE html>
<html lang="en">
<head>
 
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <title>Display Facebook page events on website</title>

    <!-- CSS will be here -->
 
</head>
<body>

    <!-- Container will be here -->

</body>
</html>

CSS code

We’re going to use Bootstrap to make our page look good. We’ll also put some custom CSS. Replace <!– CSS will be here –> with the following code.

<!-- CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="custom.css" media="screen">

Create custom.css

These are just some additional customization for our user interface. Create a custom.css file. Put the following code.

.page-header{
    margin:30px 0;
}

.nav{
    margin-bottom:30px;
}

.event_item{
    margin-bottom:50px;
}

Container code

These divs have Bootstrap classes. It will contain our Facebook page events. Replace <!– Container will be here –> with the following code.

<div class="container">
    <div class='col-lg-12'>
        <h1 class='page-header'>Display Facebook page events on website</h1>
        
        <!-- PHP code will be here -->

    </div>
</div>

PHP code

The code below gets the parameter from the URL about what to display. By default, it is “upcoming” events. The navigation.php file will help the user to select upcoming or past events.

The fb_page_events.php file will contain our request to the Facebook Graph API. Replace <!– PHP code will be here –> with the following code.

<?php 
$display = isset($_GET["display"]) ? $_GET["display"] : "upcoming";
include "navigation.php";
include "fb_page_events.php";
?>

Create navigation.php file

This file will show two tabs that will allow our users to select upcoming or past events. Create a navigation.php file and put the following code.

<?php 
$upcoming_class_active = $display=="upcoming" ? "active" : "";
$past_class_active = $display=="past" ? "active" : "";

echo "<ul class='nav nav-tabs'>
    <li class='nav-item'>
        <a class='nav-link {$upcoming_class_active}' href='index.php'>Upcoming Events</a>
    </li>
    <li class='nav-item'>
        <a class='nav-link {$past_class_active}' href='index.php?display=past'>Past Events</a>
    </li>
</ul>";
?>

Display Facebook page events

Create fb_page_events.php file

This file will contain the process of building a request to the Facebook Graph API. Create fb_page_events.php file. Put the following code.

<?php 
// specify date range will be here

// unix timestamp format will be here

// request parameters will be here

// build the api request will be here

// sort to display upcoming events will be here

// looping through events will be here
?>

Specify date range

The code below identifies the “since” and “until” dates that will be used for the API request. For upcoming events, the “since” date is the date today and the “until” date is two years from today.

For past events, the “since” date is the date from two years ago and the “until” date is the date yesterday.

Replace <!– specify date range will be here –> with the following code.

// specify date range
$year_range = 2;

if($display=="upcoming"){
	// date range for upcoming events
	$since_date = date('Y-m-d');
	$until_date = date('Y-12-31', strtotime('+' . $year_range . ' years'));
}

else{
	// date range for past events
	$since_date = date('Y-01-01', strtotime('-' . $year_range . ' years'));
	$until_date = date('Y-m-d', strtotime('-1 day'));
}

Convert to unix timestamp

Unix timestamp is required by the Facebook Graph API. We will convert the since and until dates using the code below. Replace <!– unix timestamp format will be here –> with the following code.

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

Specify request parameters

The variables below are needed to complete the parameters needed for the Facebook Graph API request. Replace <!– request parameters will be here –> with the following code.

// request parameters
$api_version = "v11.0";
$fb_page_id = "YOUR_FACEBOOK_PAGE_ID";
$access_token="YOUR_PAGE_ACCESS_TOKEN";
$fields="id,name,description,place,timezone,start_time,cover";

Specify your Facebook page ID and access token

You need to replace YOUR_PAGE_ID and YOUR_PAGE_ACCESS_TOKEN with your own.

To get your Facebook page ID, follow this tutorial. To get your Facebook page access token, follow this tutorial.

We can do this process for you but there will be a service fee of $50. Also, you will need to make us an admin of your Facebook page.

If you want to avail of this service, pay using this link. After the payment, you will receive further instructions from [email protected]

Build the API request

The code below completes the API request link and get the response using file_get_contents() function. We will also decode the response so we can easily retrieve the data. Replace <!– build the api request will be here –> with the following code.

// build the api request
$json_link = "https://graph.facebook.com/{$api_version}/{$fb_page_id}/events/attending/?fields={$fields}&access_token={$access_token}&since={$since_unix_timestamp}&until={$until_unix_timestamp}";
$json = file_get_contents($json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);

// for those using PHP version older than 5.4, use this instead:
// $obj = json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $json), true);

Sort to display upcoming events

Sorting is needed to properly display the upcoming events. The code below will let the upcoming events to be displayed from the date nearest to today up to the farthest date. Replace <!– sort to display upcoming events will be here –> with the following code.

// sort to display upcoming events
if($display=="upcoming"){
	function sortFunction($a,$b){
		if ($a['start_time'] == $b['start_time']) return 0;
		return strtotime($a['start_time']) - strtotime($b['start_time']);
	}
	usort($obj['data'],"sortFunction");
}

Loop through events

The code below will loop through each events returned from the Facebook Graph API. Replace <!– looping through events will be here –> with the following code.

// looping through events
foreach($obj['data'] as $event){
	include "extract_values.php";
	include "display_values.php";
}

Extract and display events data

Create extract_values.php file

In this file, we will extract different types of event data. Create extract_values.php file. Put the following code.

<?php 
// start date and time will be here

// basic info will be here

// location will be here
?>

Extract date and time

The code below will let us get the event’s start date and time. Replace <!– start date and time will be here –> with the following code.

// start date and time
$timezone=isset($event['timezone']) ? $event['timezone'] : "America/Los_Angeles";
date_default_timezone_set($timezone);

$start_date = date( 'l, F d, Y', strtotime($event['start_time']));

// in my case, I had to subtract 9 hours to sync the time set in facebook
$start_time = date('g:i a', strtotime($event['start_time']));

Extract basic information

The code below will let us get the event ID, name, description, and thumbnail. Replace <!– basic info will be here –> with the following code.

// basic info
$eid = $event['id'];
$name = $event['name'];
$description = isset($event['description']) ? $event['description'] : "";
$pic_big = isset($event['cover']['source']) ? $event['cover']['source'] : "https://graph.facebook.com/{$api_version}/{$fb_page_id}/picture?type=large";

Extract location

Here we will get the event’s complete address or location. Replace <!– location will be here –> with the following code.

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

$location="";

if($place_name){ $location.="{$place_name}"; }
if($city){ $location.= $location ? ", {$city}" : "{$city}"; }
if($country){ $location.= $location ? ", {$country}" : "{$country}"; }
if($zip){ $location.= $location ? ", {$zip}" : "{$zip}"; }

if(empty($location)){
    $location="Location not set.";
}

$complete_event_add="{$location}";

Create display_values.php

The code below will let us display an event item with data we extracted earlier. Create display_values.php file. Put the following code.

<?php 
echo "<div class='row event_item'>
    <div class='col'>
        <img src='{$pic_big}' class='card-img-top' alt='...'>
    </div>
    <div class='col'>
        <h2 class='card-title'>{$name}</h2>
        <p class='card-text'>
        {$start_date} at {$start_time}
        </p>

        <p class='card-text'>
        {$complete_event_add}
        </p>

        <p class='card-text'>
        {$description}
        </p>
        <a href='https://www.facebook.com/events/{$eid}/' target='_blank' class='btn btn-primary'>More info</a>
    </div>
</div>";
?>

What People Say About This Code?

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

From Blog Comments

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

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

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

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

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

From Emails

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

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

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

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

From Facebook Messages

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

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

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

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

Download the Complete Source Code

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

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

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

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

Do you need more reasons to download it?

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

Thank you for supporting our projects!

What’s Next?

Today we have learned how to show your Facebook page events on your website.

Did you know that you can also display Facebook photo albums and photos on your website?

Let us go to the next tutorial: How to display Facebook page photo album on website?

Related Source Codes

We have more tutorials related to social media APIs. Click here.

Some Notes

Found An Issue?


If you found a problem with this code, please send us an email. Before you send an email, please read our our code of conduct. Our team's email address is [email protected]


Please be descriptive about your issue. Please provide the error messages, screenshots (or screen recording) and your test URL. Thanks!


Subscribe to CodeOfaNinja


Receive valuable web development tutorials to your email. Subscribe now for FREE!



Thank You!

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

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? Email our team at [email protected]