As promised, here is the part 2 of our tutorial to create a Facebook WordPress plugin. Thanks a lot for your feedbacks.

Be sure to checkout part 1 before

Before starting off, a special thanks to Ovidiu Turean who made a pull request to the repository for the admin side developed in this part 2.

The complete code of this tutorial can be found in the same repository as part 1 under the branch V2.

So what’s on the menu?

  1. Simple AJAX powered admin page to save the Facebook app ID and secret
  2. Sending an email upon new registration in order to provide the password and username to the user
  3. CSS styling of our Facebook button

Improvement 1: creating a new WordPress page for the plugin Settings

In order to create an admin page for our plugin, we will need to re-organize it so everything is clean and make sense.

So what did we changed?

  • alka-facebook.php is the plugin main file, it’s the one called by WordPress whenever the plugin is loaded
  • assets/ is a folder that will contain all our images, javaScript files as well as stylesheets (.css)
  • classes/ contains 2 classes called in alka-facebook.php, one for the API connection and user creation / login. The other is only for the admin page.

Let’s dive in the details by starting with the main file:

As you can see, the main difference with part 1 is that this file is just here to call other files. The Facebook SDK and then our plugin classes. We define as well 2 constants that will be used to retrieve the different files within the plugin.

  • ALKA_FACEBOOK_PATH for the PHP includes
  • ALKA_FACEBOOK_URL for the .js, .css and image calls from our browsers

Once this done, we can create our admin page, using the brand new AlkaAdmin.php file. Our admin page is really simple, 2 fields (Facebook App ID, Facebook App Secret), the callback url to help the user. We save everything using AJAX so we don’t have to reload the page. Therefore we will also use a WordPress Nonce to add an extra security layer.

So as you can see our class’s constructor will call 3 main methods: addAdminMenustoreFacebookAdminCreeds and addAdminScripts.

Firstly, we use addAdminMenu to register our new page for WordPress:

As you can see, there is another callback to a new method (adminlayout) that will handle the HTML displayed within this page. You can load an other file to make your plugin even more clean. For the sake of simplicity, the HTML will be loaded within the class method (boooo…)

The 2 static methods we call from the AlkaFacebook class (see part 1 of this tutorial) will be defined later:

  • AlkaFacebook::getCredentials() returns the saved credentials from the database as an array
  • AlkaFacebook::getCallbackUrl() returns the callback URL that must be provided  to Facebook through the app portal

Once this done, we can enjoy a clean admin page for our plugin:

But nothing happen when we click the save button so far, which is (let’s be honest) quite an issue!

In order to save the data, we’ll add a javaScript file to the WordPress admin using the method: addAdminScripts(). This file will just “listen” to the admin actions, whenever the button is pushed, a request is made to your server. WordPress will redirect the request to our class’s method storeFacebookAdminCreeds(). That easy.

We enqueue our new javaScript file: assets/js/admin.js (you need to create it) using our constant define earlier.

As you can see we also pass 2 PHP variables to our JS file using an object  named: alka_facebook_admin.

We can know fill in the JavaScript file, we watch for the user click, build our request and send it using Ajax:

The result is displayed through a basic alert(), but this can be changed with something more user friendly of course.

It’s now time to save the data we received from the page in our database using a handy method: storeFacebookAdminCreeds() which is linked to our WordPress ajax hook: alka_store_admin_creeds sent in our request. This is possible with this action we’ve added at the beginning in our constructor:

So the method below just takes the data sent through the Ajax request, validate them and save them in the wp_options table.

That’s it! We can now receive and save the Facebook App ID as well as the Facebook App Secret from the WordPress admin dashboard. Cool! 

We now need to update the AlkaFacebook.php class defined in the part 1 of this tutorial to no longer use private attributes but rather our saved option. In order to get the Facebook App ID and secret.

In the same way, we will create the method that returns the site callback url for Facebook (which was also an attribute before):

We can now use them by re-defining our methods within the same class:

And lastly, for the credentials:

Done! Our API connection is now using our options from the plugin’s options page.

You can test on your side to make sure it’s working as expected.

Improvement 2: sending the email to the user

For this one, you will need server to get the email sent as your Localhost probably don’t have any email driver.

We are simply gonna add a new method in createUser() method after the meta and before we log in the user.

Now, it’s time to create this new method in our AlkaFacebook class:

We simply use the wp_mail() function from WordPress to do the job for us. This function requires 4 parameters, you can find all the details on the documentation page related to that function.

You are free to customize the content and even design your own template. Note that we pass the username, password and email as method arguments to be sure we send the right data.

Improvement 3: designing our button

In part 1, the shortcode was just displaying a simple link, we’ll create a brand new button that’d impress any of your visitor.

The first thing we want to do it to change the shortcode’s HTML output:

As you can see we’re adding a new icon, which can done be downloaded from the Facebook Brand Resources page. Pick up any icon from the .zip your download (possibly a white one) and place it in assets/images/, renamed as fb-logo.png.

We can also create a new css file assets/css/button-style.css:

We now need to add our new css file whenever the page is loader. Similarly to the admin side, we just create a new action in the AlkaFacebook class’s constructor

So it looks like:

We just have to enqueue the stylesheet with the method: addButtonCSS()

Here again, we are making great use of the constants defined at the beginning of this tutorial.

This is the expected result on a new page called “Facebook” containing only the shortcode. On the default WordPress theme:

 

Lastly, regarding the Facebook avatar and how to get it upon registration, well we didn’t developed it in this part for a simple reason. As or right now, I have looked several plugins doing so and I find the process very “barbarian”. It’s just a filter on the get_avatar() function  to replace the path with a link to Facebook containing the user ID. Simply because it’s managed by Gravatar on WordPress. It’d be better, if we do it, to focus only on BuddyPress as their is a deeper avatar integration. With an upload process for example, which is not here by default on WordPress.

Any question? Fire away in the comments 🙂

 

Share

Written by

2F

<p>Lead developer at Alkaweb.</p>

9 Comments

  1. v2 doesn’t have session issue but still not saving details or creating wp admin..

  2. And also it doesn’t work if callback was set into http://localhost/site/wp-admin/admin-ajax.php?action=alka_facebook . It only works if the button is located in the same call back URL

    • Hello,

      What do you mean by “the button is located in the same call back URL”? That callback is what you should provide to Facebook and is not a page. It’s a resource to handle the Facebook request.

  3. I get an error “Sorry, that username already exists!” for existing users.

    • Hello,

      Where do you get that error? That is likely coming from:

      $_SESSION['alka_facebook_message'] = $new_user_id->get_error_message();

      It means that the generated username:

      $username = sanitize_user(str_replace(' ', '_', strtolower($this->facebook_details['name'])));

      Is creating an username that already exists on your side but it cannot be logged in because it was not created through Facebook.
      You can prefix it to avoid that: $username .= 'fb_'.$username;

      Cheers

  4. since the plugin store the session token, can we use it to retrieve the updated fb user’s profile info again?

Leave a Reply

Your email address will not be published.Required

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

You May Also Like to Read