Screen Shot 2013-09-24 at 5.52.18 PM I want my quote generator to allow people to automatically post a random quote to their Facebook wall. Eventually, I want them to set it up to post at certain times automatically for them, but for now, I just wanted them to be able to click a link and it post a random quote to their Facebook wall for them.

You first need to set up a Facebook app. You can find those instructions here. You will need to do this to get the Facebook App ID and App Secret.

Once you have those, you can place the following code in the child template page. For instance, I have a template page in my theme named page-facebook-quotes.php I put the following code in that page. Remember to replace ‘your_app_id’ and ‘your_app_secret’ with the codes you got from creating your Facebook App.

//
session_start();
ob_start();
 //facebook application configuration
    $fbconfig['appid' ] = "your_app_id";
    $fbconfig['secret'] = "your_app_secret";
    try{
        include_once ('src/facebook.php');
    }
    catch(Exception $o){
        print_r($o);
    }
    $facebook = new Facebook(array(
      'appId'  => $fbconfig['appid'],
      'secret' => $fbconfig['secret'],
      'cookie' => true,
    ));
 
    $user       = $facebook->getUser();
    $loginUrl   = $facebook->getLoginUrl(
            array(
                'scope'         => 'publish_stream'  // This allows you to publish something to their wall
            )
    );
 
    if ($user) {
      try {
        $user_profile = $facebook->api('/me');
        $user_friends = $facebook->api('/me/friends');
        $access_token = $facebook->getAccessToken();
      } catch (FacebookApiException $e) {
       // d($e);
        $user = null;
      }
    }
    if (!$user) {
        echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
        exit;
    }
 $quote = file_get_contents('http://ourprosperouslife.com/api?id=quote');  // The information to be posted to their wall

 $args = array(
    'message' => strip_tags($quote),
    'link'   => 'http://ourprosperouslife.com/facebook-quotes',
    'caption' => 'Get your own quote!',
    'description' => strip_tags($quote),
    'picture'   => 'http://ourprosperouslife.com/opl128x128-2.png',
);
$post_id = $facebook->api("/me/feed", "post", $args);
header("Location: http://facebook.com/".$post_id['id']);  // redirect them to the post on facebook
//

This code will produce something like this:

Screen Shot 2013-09-24 at 5.52.18 PM

You can see it in action here.

1 thought on “Post to a Facebook Wall from my WordPress Website”

  1. Pingback: Post Something to a Facebook Page I Manage From My WordPress Site - Cullen Web Services

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top