Blog

Create your own WordPress shortcode that pulls posts from facebook page

Hello there!

In the same vein as our previous post that shows how you could create your own shortcode to pull tweets from a user, we’ve decided to make a similar post that shows how you could pull content from a facebook page and integrate it into your WordPress site.

Sometimes it makes more sense to create custom shortcode in WordPress as opposed to creating a full on WordPress plugin. One might consider it overkill to create a WordPress plugin to accommodate integrating a feed such as this. If you envision needing a visual interface to change options such as styling, css and Facebook API keys then you might want to go the plugin route.

Creating shortcode is a very efficient and lean way to accomplish full WordPress customization and integration without the overhead that may be required to create a custom WordPress plugin.

First things first is we want to create a facebook app. Because we are going to be pulling data from a public facebook page, you dont need to be requesting access permissions other than what should be selected by default when you create a new app. Head on over here to create your app.

Once you have created your app and have your appID and secret, you can download a copy of the Facebook SDK and integrate it in your WordPress functions.php file :

require_once get_template_directory_uri() . '/facebook/facebook.php';

Once we have that line implemented in your functions.php, we can focus on creating the custom shortcode which will be connecting to facebook via the API, pulling the public posts from your page, formatting the results and displaying them however you see fit on wherever you will be using the shortcode.

The shortcode in our example will only receive one option: “number”. This would be the number of posts to pull and display. Obviously the sky is the limit with the number of options the shortcode can receive. You can generate custom CSS classes/IDs to format and style the output. Or you could filter the results to only display posts with certain keywords or posts that were posted within certain date ranges. I believe Facebook may not allow you to go back too far in terms of pulling archived posts.

To declare the shortcode options, we typically would put that at the top of the shortcode function :

function getFacebook($atts) {
	extract(shortcode_atts(array(
        'number' => '5'
    ), $atts));

To add more shortcode options, you simply would need to add the default variables to the shortcode_atts array. Next in the function we would need to define the appId and secret that you recently generated when creating your new facebook app :

// connect to app
$config = array();
$config['appId'] = 'xxxxxxxxxxxxxx';
$config['secret'] = 'xxxxxxxxxxxxxx';
$config['fileUpload'] = false; // optional
// instantiate
$facebook = new Facebook($config);

This is fairly self explanatory so I wont get too much into it. The next line is important, though :

$feed = $facebook->api('/yourFBpageURI/feed');

You need to replace “yourFBpageURI” with the URI of your actual facebook page. This is what the code uses in order to tell facebook which content to pull. Depending on what the default facebook app permissions are when you first attempt to pull the data, you might need to actually authorize the facebook app to interact with your facebook page. The most common error you may encounter would be permissions errors. I’ll show you how to diagnose those errors further down.

In the above code, you are basically putting all the contents of the results of the page feed query into the $feed PHP variable. This will be a massive multi dimensional array that you will have to sort through in order to get the content that you need.

For the purposes of this exercise, we will be pulling the following items from the feed : link to facebook post, image from post and post message. If you wanted to see what other information that you might want to use in the feed array, you could simply dump the entire array to see :

var_dump($feed);

One additional use for using var_dump for the $feed variable will be when you are diagnosing problems interacting with facebook. Some scenarios may have a facebook error message returned into the feed variable. You may see this message when using the shortcode but it might be helpful to var_dump the variable to get all the information possible.

What we need to do at this point is loop through the massive $feed array and build a variable that we will use to return the output when the shortcode is called. This returned variable will be called $out in our example.

$i = 0;
	
if (count($feed["data"]) >= $number) {
	for ($i=0;$i<$number;$i++) {
		$out .= '
'. make_clickable($feed['data'][$i]['message']) . '
'; } } else { for ($i=0;$i
'. make_clickable($feed['data'][$i]['message']) . '
'; } }

The important thing to note here is the if-statement at the top of this snippet. We want to make sure that the number of results isn’t less than the number of results specified as a shortcode option. If there’s only 3 facebook page posts but you specified 5 as a limit, that might cause problems. So we have two conditions for the loop that builds $out : 1) If the number of posts is greater than or equal to the number limit option and 2) If the number of posts is less than the number limit option.

If you look at either for-loop, you will see that we are simply building a div container for each feed post. You can style this however you like, which is the main advantage to doing it this way instead of using a 3rd party WordPress plugin!

You can see that the $feed is a 3 dimensional array. If you did end up using var_dump($feed) you will see the results may be overwhelming. Once you wrap your head around what Facebook is returning you should have an easy time deciding what and how to manipulate the results.

The final step in this function is to return the $out variable. Thats pretty self explanatory. You also will need to declare the actual shortcode that calls the function :

add_shortcode('one_fb', 'getFacebook');

So you can see the full code from start to finish here :

function getFacebook($atts) {
	extract(shortcode_atts(array(
        'number' => '5'
    ), $atts));
    
	// connect to app
	$config = array();
	$config['appId'] = 'xxxxxxxxxxxxxx';
	$config['secret'] = 'xxxxxxxxxxxxxx';
	$config['fileUpload'] = false; // optional
	// instantiate
	$facebook = new Facebook($config);

	$feed = $facebook->api('/yourFBpageURI/feed');
	$out = '
'; $i = 0; if (count($feed["data"]) >= $number) { for ($i=0;$i<$number;$i++) { $out .= '
'. make_clickable($feed['data'][$i]['message']) . '
'; } } else { for ($i=0;$i
'. make_clickable($feed['data'][$i]['message']) . '
'; } } $out .= ''; return $out; } add_shortcode('one_fb', 'getFacebook');

In order to use the shortcode you simply would need to paste the following wherever you want the feed to show up in WordPress :

[one_fb number="5"]

I hope this helps you in creating your own shortcode! You can see by how simply we integrate the Facebook SDK that you really can integrate anything that has a public and open API with WordPress using simple shortcode. Going the shortcode route may be a bit more overhead than finding a third party WordPress plugin, but in the end it will allow you to customize everything 100%. Typically with plugins they may not offer all the customization you (or your client) may be looking for. Add on top of that the security and best practices considerations of relying on third party plugins and it really makes your options very clear 🙂