File Included In Wordpress Header Not Available In Body
I included the Facebook SDK in Wordpress header.php, and within this file, the SDK works fine. However, when I try to use the SDK in a page that uses the header, I get errors saying certain objects weren't defined etc. As if the file was never included.
Basically, I can get the user's FB info to display on the header of the page, but nowhere else.
EDIT: Here's part of the header.php file:
<?php
include_once('facebook-php-sdk/src/facebook.php');
$config = array();
$config['appId'] = '***********';
$config['secret'] = '***********************';
$config['cookie'] = true;
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$user_profile = $facebook->api('/me','GET');
echo $fbUsername = $user_profile['name'];//WORKS HERE
?>
But on a page:
<?php
get_header();
echo $fbUsername;//not working;
?>
Solutions
I think you are including this header in every file you have. So, a new facebook object created each time- so may be the new facebook session- that's the wrong way to do it!
The error:
"An active access token must be used to query information about the current user
is due to the fact that there is not current user in the session so you cannot call any api like:
/me...
So dont create FB object again and again, instead create it only once - at the start of the application. Use that same
$facebook
and then main thing- the session/active
access token
can expire at any time, so you should do a check:
$user_id = $facebook->getUser();
if($user_id)
$user_profile = $facebook->api('/me','GET');
else
// get the login url and create new session
(you can follow sdk sample for the same)
You can also save the name or other fb info you are using in your session variable once just like-
session_start();
$_SESSION['fb_user_name'] = $user_profile['name'];
instead of fetching them again and again.