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

20 Most asked Odoo Interview Questions

Odoo Accounting Interview Questions

Know More »
shopify sections and blocks

How to create Custom Sections in Shopify[Dawn Theme]

Are you looking to customize your Shopify store beyond the standard templates and themes? Do you want to create unique...

Know More »
fix japanese keyword hack

Looking for Video Tutorials?

Explore Our Youtube Channel for in-depth Tutorials

Yes I am Curious »