Category Archives: How-to

How To Add a Custom Field via WordPress plugin

How To Add a Custom Field via WordPress plugin?

Sometimes we need to add custom data for our posts and pages other than title and content especially when ones become comfortable with WordPress, there is an urge to do something experimenting for exciting features using WordPress custom field.  for  Suppose you are using Custom Post Types for your book store and want to save the Book price as well. You have added title and description but for price you will add a custom field. Today we are going to gain an understanding of  how you can add custom fields via WordPress plugins. In modern WordPress development, these kinds of functional stuff should be done via plugins instead of coding in WordPress themes.

Before moving forward please download the plugin from here. Please open the class file “class_custom_field.php”.

I will explain every code snippet step by step.

function init_customField() {
new customField();
}

The above function is simply getting an instance of the class and returning it.

if ( is_admin() ) {
add_action( 'load-post.php', 'init_customField' );
add_action( 'load-post-new.php', 'init_customField' );
}

This code snippet is saying that when a post is to be edited or a new post is to be made get an instance of “customField” class and getting an instance is of course means to initialize and render the text field in the posting page.

“load-post” and “load-post-new” are two new hooks.

public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
add_action( 'save_post', array( $this, 'save' ) );
}

Class constructor is adding functions to the hooks for rendering and saving the data.

public function add_meta_box( $post_type ) {

$post_types = array('post', 'page'); //limit meta box to certain post types
if ( in_array( $post_type, $post_types )) {
add_meta_box(
'my_meta_box_name'
,__( 'My Meta Box Headline', 'myplugin_textdomain' )
,array( $this, 'render_meta_box_content' )
,$post_type
);
}
}

The “add_meta_box” is in fact the responsibility to render the text field. The first argument is setting “id“, the second argument is setting title, the third argument is giving the definition that how will it be and the fourth argument is setting the screen is it a “page” or a “post” where this custom field will be rendered on.

public function save( $post_id ) {
//code goes here
}

Inside the “save” function first, we are checking whether “nonce” is set. “nonce” is put in the form for security reasons. You can read about it from here. Then we are verifying whether it is a valid “nonce”. Then simply checking whether the current user is authorized to perform this action. Then we are sanitizing the data and saving or updating the data using “update_post_meta” giving a key. Because with this key we will later retrieve our data.

public function render_meta_box_content( $post ) {
//code goes here
}

Inside “render_meta_box_content” we are generating “nonce”. Then getting the data if it was set using “get_post_meta” function and putting this value in the text field and rendering the text field.

And all done! Adding custom fields to WordPress is like doing some extra coding and in result you get the specific features for a particular post that may need some extra informational data.

how to integrate facebook login with wordpress, facebook integration with wordpress

How to Integrate Facebook login to WordPress?

Facebook API integration with a site improves your site’s social rank. We can integrate a like button to our website or a comment box, which is quite easy. A bit of a messy job comes when we get a requirement to create an app for a website and then integrate it. There may be many reasons to create an app. May be you want to give the users to signup to your site using their Facebook account or you want to engage more traffic from your social circle to your site/blog using Facebook login.

So today we are going to sum up the tried and tested steps involved in integration of  Facebook login to WordPress manually without using any plugin. So let’s begin!

To integrate graph API to WordPress, we first need to create an app on Facebook using developer page. And then start it straight away.

Step 1:

Login to your Facebook account and go to developer page. Then Click on Add New App.

Integrate Facebook Login to WordPress - Add a new App
Integrate Facebook Login to WordPress – Add a new App

Step 2:

It will open a light box asking you to select the platform. Just select www

Integrate Facebook login to WordPress - select website
Integrate Facebook login to WordPress – select website

Step 3:

Give a name to your app

Integrate Facebook login to WordPress - Add name of App
Integrate Facebook login to WordPress – Add name of App

Step 4:

You can select any type

Integrate Facebook login to WordPress - Select type of App
Integrate Facebook login to WordPress – Select type of App

Step 5:

Stop here, please. Go to your WordPress theme and create a template file, let’s say “fb.php”.

Integrate Facebook login to WordPress - Create WordPress template file
Integrate Facebook login to WordPress – Create WordPress template file

Step 6:

Please get back to your Facebook page and copy this code and paste it into your fb template file.  And you can see you have to give your site URL which in my case is localhost/wordpress. After putting your site URL click next.

Integrate Facebook login to WordPress - Facebook SDK code
Integrate Facebook login to WordPress – Facebook SDK code

Step 7:

Then you will see this page, just copy the code and put it into your fb template.

Integrate Facebook login to WordPress - Facebook HTML5 code
Integrate Facebook login to WordPress – Facebook HTML5 code

Your template file will look like this.

Integrate Facebook login to WordPress - Facebook Template for WordPress
Integrate Facebook login to WordPress – Facebook Template for WordPress

Step 8:

Now go to your WordPress admin and create a page, let’s say “Facebook”, from the WordPress admin and assign the fb template to this page. Open your page and your page will be looking like this.

Integrate Facebook login in WordPress - Facebook Page for WordPress
Integrate Facebook login in WordPress – Facebook Page for WordPress

So you have done a good job but as you know our objective is still not achieved.

Step 9:

If you go down of developer page you will see these boxes. Let’s integrate login to our site. Click on login box.

create fb app11
Integrate Facebook login img-10

It will open a new tab and on that page you will find a complete code for login to put into your facebook template file.

Facebook Login code for the Web Using the JavaScript SDK
Facebook Login code for the Web Using the JavaScript SDK

Step 10:

After putting the code, just find this “{your-app-id}” and put your app id. You can get your app id by navigating to this page “My apps

Save your fb template and reload the page.

Ah, an error, but it was important to show you. See it is saying the URL is mismatching. But what is it about? Now go to “My apps” page and edit your app settings on edit settings page you will see the “App Domains” is empty and you should mentions your app domain over here. And we are using http://localhost/wordpress/facebook so our “App Domain” will be “localhost”. Put “localhost” in the box and click save. Now go to your WordPress page and reload it.

Awesome, now you can see something like this.

create fb app14
Integrate Facebook login img-12

There are three things to take care of.

1: Which of the things you are taking from user.

2: User can edit and select which of the things he wants this app to access.

3: Facebook is assuring the user that this app will not put anything on your wall (Unless you give it permissions to do so).

After clicking OK, you will get a “response object” from Facebook. This object will have the whole detail. If you open your browser’s console you will see some sub objects of main object. You can console the whole “response object” to see the whole information it is carrying.

Integrate Facebook login in WordPress - Login now
Integrate Facebook login in WordPress – Login now

You can put the post request into this block or wherever you need. In our Test example, we are using TestAPI() function which fetches the user information from Facebook and shows you in console.log

"if (response.status === 'connected'){}"

You can make an ajax call at this point and store user information in your WordPress database and create Facebook login user as a WordPress user as well.  There should be part 2 of this tutorial which explains that how we make an ajax call and create Facebook login user as WordPress user as well. We will be sharing it soon seeing how much people are interested in it so looking forward to it, and you can ask anything related to integration of  Facebook login to WordPress in the comment box, will surely be helpful to all of our great readers!

 

How to make WordPress database secure by changing default WordPress table prefix?

How to make WordPress database secure by changing default WordPress table prefix?

WordPress Database Security is the most important thing. Every single piece of information stored in it, which makes hackers and bots to target for stealing information by applying SQL Injection.

WordPress Database uses a default table prefix value “wp_” for all of its database tables. Typically, every website that is running WordPress will have its database tables with this prefix and this can surely be used by the hackers or malicious bots to guess your database table names. That’s why the smartest thing to do while creating a WordPress website is to change the prefix of the database, which can be done easily.

If you forgot to change the prefix of the database table while creating your WordPress website, you can do this now by following these simple steps.

Note: It’s recommended to backup your database before performing this task.

There are two simple steps you need to follow:

Step 1. By changing the wp-config.php file:

  • Go to your WordPress root directory and search for a file named “wp-config.php”.
wp-config.php file
wp-config.php
  1. Open “wp-config.php” in any code editor and search for “$table_prefix  = ‘wp_’;”
  2. Change “wp_” prefix to something like “Br1G@de” or anything you like.
WordPress database table prefix
Table Prefix
Note: Only alphabets, numbers and underscores.

Step 2. Change database table names:

Now you need to access your database using phpMyAdmin and change the table name’s prefix with the new one we entered in “wp-config.php” file.

You will find the phpMyAdmin link in cPanel under Databases section.

phpMyAdmin Database
phpMyAdmin

By default there are normally total 11 tables listed

WordPress Database Default Tables
Default Tables

Select the SQL tab and run the simple queries and use the prefix you add in “wp-config.php” file.

RENAME table `wp_commentmeta` TO `Br1G@de_commentmeta`;
RENAME table `wp_comments` TO `Br1G@de_comments`;
RENAME table `wp_links` TO `Br1G@de_links`;
RENAME table `wp_options` TO `Br1G@de_options`;
RENAME table `wp_postmeta` TO `Br1G@de_postmeta`;
RENAME table `wp_posts` TO `Br1G@de_posts`;
RENAME table `wp_terms` TO `Br1G@de_terms`;
RENAME table `wp_term_relationships` TO `Br1G@de_term_relationships`;
RENAME table `wp_term_taxonomy` TO `Br1G@de_term_taxonomy`;
RENAME table `wp_usermeta` TO `Br1G@de_usermeta`;
RENAME table `wp_users` TO `Br1G@de_users`;
 Note: If you have plugins installed, you have to make changes to those tables as well same we just did it with default WordPress tables.
WordPress, WordPress development

How To Create Custom Post Types In WordPress Admin?

Now a days, WordPress is not just a blogging platform. From past few years, WordPress has become a robust content management system. By default, WordPress has two main post types:

  • Post
  • Pages

but you can create your own custom content types you want, these custom content types are referred as custom post types.  So when the WordPress is giving you the option to go beyond blogging platform and line up your content management system so there is no reason not to create custom post type WordPress. So today we will show you how you can easily create your own custom post types.

What is custom post type?

WordPress has many post types like:

  • post
  • page
  • attachment
  • revision
  • menu

by default. But, sometimes you might be requiring some custom post types according to your requirements. For example, You may need to create a custom post type for products for an e-commerce website, for assignments for an e-learning website, or for movies for a review website.

How to create custom post types?

To create a custom post type, you can either create a new custom post type plugin or if you are working with themes you can paste the following code in Active theme of “functions.php” file.

add_action( 'init', 'custom_post_type' );

function custom_post_type() {
    register_post_type( 'php_book',
        array(
            'labels' => array(
                'name' => __( 'Books' ),
                'singular_name' => __( 'Book' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'books'),

        )
    );
}

First, we will walk you through with a fully working example of custom post type plugin so you understand how it works, take a look at below code. Create a new file in /wp-content/plugins/custom_post_types_plugin.php and paste the following code in it.

<?php

/*
Plugin Name: Custom Post Types Plugin By WPBrigade
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: Example to create your own custom post types plugin.
Version: 1.0
Author: WPBrigade
Author URI: http://www.twitter.com/WPBrigade
License: A "Slug" license name e.g. GPL2
*/

add_action( 'init', 'custom_post_type' );

function custom_post_type() {
    register_post_type( 'php_book',
        array(
            'labels' => array(
                'name' => __( 'Books' ),
                'singular_name' => __( 'Book' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'books'),

        )
    );
}

 

To create a new post type, we will use the register_post_type() function.

In “custom_post_type()” function we registers a post type with name of “php_book” with an array of arguments. These arguments are the options for our custom post type and has two parts, first array has label name of our custom post type and singular name for custom post. Second array include other arguments like public visibility, archive  and slug that will be used in URLs for this post type. You can learn more about using slug in WordPress here.

And what if you have no mood to do the coding thing, so there is always a option to go for custom post type plugin . For this  we need to activate our WordPress custom post type plugin from “Plugins” area.

Activate Plugin

 

After activating the Custom Post Type Plugin from plugins page you will see the new Custom Post Type with the name “Books” in admin area.

wordpress admin panel
wordpress admin panel

 

To add a new post you need to go to Book post from admin panel and click Add New.

Add New Book
Add New Book

You can see the entries of book types like this.

Books - Custom Post Types
Books – Custom Post Types

Of course, you want to see the added books in front end of your site. If you will see the page in front end you will be having a 404 error, probably.

404 Page Not Found - Custom Post Types
404 Page Not Found – Custom Post Types

Why? Because, you have to rearrange the rewrite rules as you have added new route/slug for book type entries.

Go to your permalink settings, change them to default and then again to your desired URL structure. Now if you will open the page to view the added book, you will surely be seeing the correct page.

Archive Page - Custom Post Types
Archive Page – Custom Post Types

 

See the list of all of the arguments that can be passed to register_post_type.

interact with WordPress APis, how to add a custom field via wordpress

How To Interact With An API Using WordPress Standard Functions?

To interact with APIs is a very common thing in Web Development, WordPress gives us the utility functions to interact with APIs. As you know to interact with an API requires good knowledge of cURL and many other things, WordPress takes this responsibility and wrap the inner stories into utility functions for you.

wp_remote_get is the function that gets the data for you from an API. All you have to do is just put the endpoint as an argument and voila! It’s magic.

This function basically takes two arguments
1. $url – Resource to retrieve data from. This must be in a standard HTTP format
2. $args – OPTIONAL – You may pass an array of arguments in here to alter behavior and headers, such as cookies, follow redirects, etc.

Let’s make a call to GitHub API and see what happens.

$response = wp_remote_get( 'https://api.github.com/users/ifiwfi' );

It will retrieve the following data:

Array
(
[headers] => Array
(
[server] => GitHub.com
[date] => Thu, 12 Mar 2015 13:46:33 GMT
[content-type] => application/json; charset=utf-8
[connection] => close
[status] => 200 OK
[x-ratelimit-limit] => 60
[x-ratelimit-remaining] => 58
[x-ratelimit-reset] => 1426171579
[cache-control] => public, max-age=60, s-maxage=60
[last-modified] => Wed, 04 Mar 2015 18:42:08 GMT
[etag] => W/"87972c50f954668862db38480dab5c78"
[vary] => Array
(
[0] => Accept
[1] => Accept-Encoding
)

[x-github-media-type] => github.v3
[x-xss-protection] => 1; mode=block
[x-frame-options] => deny
[content-security-policy] => default-src 'none'
[access-control-allow-credentials] => true
[access-control-expose-headers] => ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
[access-control-allow-origin] => *
[x-github-request-id] => 6E271E7B:376A:68977C5:550198B8
[strict-transport-security] => max-age=31536000; includeSubdomains; preload
[x-content-type-options] => nosniff
[x-served-by] => 07ff1c8a09e44b62e277fae50a1b1dc4
[content-encoding] => gzip
)

[body] => {"login":"ifiwfi","id":6972531,"avatar_url":"https://avatars.githubusercontent.com/u/6972531?v=3","gravatar_id":"","url":"https://api.github.com/users/ifiwfi","html_url":"https://github.com/ifiwfi","followers_url":"https://api.github.com/users/ifiwfi/followers"}
[response] => Array
(
[code] => 200
[message] => OK
)

[cookies] => Array
(
)

[filename] => 
)

If you want to get the body part from the response, you can do like this:

$response = wp_remote_get( 'https://api.github.com/users/ifiwfi' );
$body = wp_remote_retrieve_body( $response );

If you want to get the response code, you can do like this:

$response = wp_remote_get( 'https://api.github.com/users/ifiwfi' );
$http_code = wp_remote_retrieve_response_code( $response );

The next part of the interaction is to post the values to an API. You can use this function wp_remote_post. This function takes the first argument the URL on which the data has to be posted and the second argument the data which has to be posted. The data should be in the key value pair array. As GitHub doesn’t let us post data so we just assume some URLs.

$body = array(
'name' => 'Irfan Ahmed',
'profession' => 'Software engineer',
'email' => '[email protected]',
'subject' => 'How to post data to a form or API',
'comment' => 'Hey, I learned a lot from this article.'
);

$args = array(
'body' => $body,
'timeout' => '10',
'redirection' => '3',
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'cookies' => array()
);

$response = wp_remote_post( 'http://yourwebsite.com/contact/', $args );

The last important thing is to make any kind of call. Like you want to delete an object from database table using the API. It will be done like this:

$args = array(
'method' => 'DELETE'
);
$response = wp_remote_request( 'http://api.yourwebsite.com/object/to/delete', $args );

This is the most easiest and interactive way to use an API using WordPress using standard functions. Feel free to comment below and let us know how this tutorial helps you.