Integrated Tech Solutions

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

By - Admin 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 »

WordPress or React – How to choose the best Tech stack for your website

Are you still confused in picking the best Tech stack for your website? Choosing the right tech stack for your...

Know More »

5 Tips to Pick the Most Engaging Live Chat for Your Website

In today’s fast-paced digital world, providing excellent customer service is a key differentiator for businesses. One of the most effective...

Know More »