I figured out how to post something from my WordPress site to a Facebook time line, but I also want to be able to post to a Facebook Page that I manage as well. I would like to post some of the random quotes I’ve generated to my Facebook page.
The code is similar to the code I used to post to a wall or time line, but I have to know on which page to post and if the current user has permission to do so. Here’s the code I used:
//
session_start();
ob_start();
/**
* Edit the Page ID you are targeting
* And the message for your fans!
*/
$page_id = 'YourPage';
$message = 'my message!';
$fbconfig['appid' ] = "YourAppId";
$fbconfig['secret'] = "YourSecret";
require 'src/facebook.php'; // use the path to facebook.php on your site
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id?fields=access_token"); // get access token
if( !empty($page_info['access_token']) ) {
$args = array( // set up arguments for the post
'access_token' => $page_info['access_token'],
'message' => $message
);
$post_id = $facebook->api("/$page_id/feed","post",$args); // make the post
header("Location: http://facebook.com/".$post_id['id']); // go to Facebook and show the post
} else { // If you can't get the access token, then the user must not have given us permission
$permissions = $facebook->api("/me/permissions"); // get permissions
if( !array_key_exists('publish_stream', $permissions['data'][0]) ||
!array_key_exists('manage_pages', $permissions['data'][0])) { // check for the correct permissions
// We don't have one of the permissions
// Alert the admin or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
}
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>"; // get the permissions
}
//
This will create a post on a page ($page_id) with the message 'my message!'. Note: if you try to execute the code more than once, you could get a duplicate message error. I’m not sure how long it is before you can post the same message twice because I was too impatient to wait.
