Integrated Tech Solutions

How to Display Facebook Posts on Website Using Graph API [PHP]

By - Admin, Updated on October 9, 2022

Go to Facebook Developers Page & Create a New app.

Open Graph API Explorer Tool & Generate Access Token for your app

Generate a Long Lived Token Using Access Token tool

Copy the Access Token Created above & Use in your PHP Code as shown below

<?php $user_acces_token = '<USER_ACCESS_TOKEN>';
$page_token = getFBPageAccessToken('<PAGE_ID>',$user_acces_token);
$facebookData = file_get_contents('https://graph.facebook.com/v14.0/me/feed?fields=full_picture%2Cmessage&access_token='.$page_token);
$facebookArr = json_decode($facebookData,true)['data'];
foreach($facebookArr as $singlePost){
       if($postindex > 4){
          $facebookId =  $singlePost['id'];
$image_url = '';
$postMessage = 'Content Not found';
if (array_key_exists("full_picture",$singlePost)){
$image_url =  $singlePost['full_picture'];
									         }
									         if (array_key_exists("message",$singlePost)){
									             $postMessage =  $singlePost['message'];
									         } ?>
<a class="unif" href="https://www.facebook.com/<?php echo $facebookId; ?>" target="_blank"><img src="<?php echo $image_url; ?>" alt="" class="w-100"></a>
												  <p><?php echo  $postMessage; ?></p>
													  <a href="https://www.facebook.com/<?php echo $facebookId; ?>" target="_blank" class="float-end"></a>
												  <?php $postindex++; }?>

PHP function to Generate Page Access Token from User Access Token

/** PHP function to generate Page Access Token from User Access Token **/
function getFBPageAccessToken($pageId='',$UserAccessToken=''){
 if(!empty($pageId) && !empty($UserAccessToken)){
      
$output = file_get_contents('https://graph.facebook.com/'.$pageId.'?fields=access_token&access_token='.$UserAccessToken);
$output = json_decode($output,true);
if(array_key_exists('access_token',$output)){
return $output['access_token'];
}else{
    return false;
}
    }
}

Popular Blog Posts for PHP Developers

Keep Reading

👋 Hi, Find this Helpful? There is More

You Asked,
We made it!

fix japanese keyword hack

Step by Step Video Tutorials on trending topics in software development

Yes I am Curious »

AR in Websites – Top 3 Platforms for Bringing Augmented Reality to Your Web Experience

As technology advances, augmented reality (AR) is no longer limited to gaming or social media apps. Integrating AR into websites...

Know More »

Webhook Explained for Beginners: Everything You Need to Know

In the world of APIs, automation, and modern web applications, the term “webhook” often comes up. But what exactly is...

Know More »