Build first WordPress Plugin

WordPress plugins are small bits of code that are used to extend the functionality of WordPress. Plugins can be very useful in creating new features in WordPress or extending existing features to make them easier to use. I would like to illustrate in this tutorial how plugins work and by building a plugin from scratch. Recently, I outlined how to build and membership site in a tutorial – Building a Membership site in WordPress. In this tutorial, I highlighted the different features of a good membership site. I would like to revisit one of these features and build a plugin based on this feature. I will be building a WordPress login form plugin that enables members of your site to log in from a page. I want this plugin to achieve the following goals:

Make it easy for administrators to create a login page using a shortcode

Allow login forms to be added to any WordPress page easily

Successfully create the login form system for members

For you to understand how WordPress login functions work, I would recommend you read my previous detailed tutorial on creating a custom WordPress login page – Creating a Custom WordPress login page with Brand Identity. Let us now get started with building our first WordPress plugin.

Register WordPress Plugin

The first step when building a WordPress plugin is to register the plugin‘s name, plugin URL, plugin description, plugin version, author name, and the author URL. This is the most important step since this file tells WordPress that this is a plugin when it is uploaded in the folder wp-content/plugins.

You can substitute these values with your own, for this tutorial I have named the plugin ‘ Tuts Login Form’ You should be careful when naming plugins since if you use existing names there is a possibility you can end up with plugin conflicts, see my detailed tutorial – Causes and Solutions of Plugins Conflicts
<?php

/**

* Plugin Name: Tuts Login Form

* Plugin URI: https://theme4press.com/blog

* Description: Tutorial login form plugin.

* Version: 1.0.0

* Author: Joe Njenga

* Author URI: https://njengah.com/

*/

Create a Plugin Folder

The second step is to create a folder with the plugin’s name and save the main plugin file inside that folder and name it tuts-login-form.php. You should also create another folder inside this plugin folder and name it CSS and another folder named includes. See the image below:

Get Started with WordPress Plugins – Build Your First Plugin

Register Includes Folder in the Main File

Now we need to create the definitive path for our plugins include files where we will place all additional files that we need to be called to our main file. We create a Php function defining includes’ folder path as follows:
define('TUTS_REGISTRATION_INCLUDE_URL', plugin_dir_url(__FILE__).'includes/');

Enqueue Stylesheet and JavaScript Files

Here we now need to enqueue our CSS and JavaScript; this is the process of how stylesheet and JavaScript are added in WordPress. You can learn more on how to enqueue scripts in WordPress from – wp_enqueue_script()
//Adding frontend Styles from includes folder

function tuts_styl_incl(){

wp_enqueue_style('tuts_styl_css_and_js', TUTS_REGISTRATION_INCLUDE_URL."front-style.css");

wp_enqueue_script('tuts_styl_css_and_js');

}

add_action('wp_footer','tuts_styl_incl');

Create Shortcode Function to Add Login to Pages and Posts

Now let’s create the shortcode that will be used for publishing the login form on our pages. The following is the code that will add shortcode to our plugin. We have defined the name of the shortcode as [tuts-login-form] this is the shortcode we will use later in our pages to create the login form.
//Adding login shortcode

add_shortcode( 'tuts-login-form', 'tuts_login_shortcode' );

Create Function for the Login Shortcode and Login Form

We need to create a function to test our login shortcode and also use an If statement to test various conditions the most important – if the user is logged in. Here is a simplified breakdown:

Redirecting Logged Users to Homepage

This function tests if the user is logged in, if true the user is redirected to the home page.
if ( is_user_logged_in() ) {

wp_redirect( get_option('home') );// redirect to home page

exit;

}

          Creating the Login Form

This section creates the login form that we will be styling later to make it more appealing to the users.
<div class="tuts-login-form">

<?php if($login_fail_msg=='failed'){?>

<div class="error" align="center"><?php _e('Username or password is incorrect','');?></div>

<?php }?>

<div class="tuts-login-heading">

<?php _e("Tutorial Login Form",'');?>

</div>

<form method="post" action="<?php echo get_option('home');?>/wp-login.php" id="loginform" name="loginform" >

<div class="tuts-txt">

<label><?php _e('Login ID :','');?> </label>

<input type="text" tabindex="10" size="20" value="" class="input" id="user_login" required name="log" />

</div>

<div class="tuts-txt">

<label><?php _e('Password :','');?> </label>

<input type="password" tabindex="20" size="20" value="" class="input" id="user_pass" required name="pwd" />

</div>

<div class="tuts-btn">

<input type="submit" tabindex="100" value="Log In" class="button" id="wp-submit" name="wp-submit" />

<input type="hidden" value="<?php echo get_option('home');?>" name="redirect_to">

</div>

</form>

Complete Code for Testing Shortcode and Creating Login Form

The complete code that includes the shortcode function, the login form and the login status test should be as follows:
// function to test the login Shortcode

function tuts_login_shortcode( $atts ) {

//if user is logged in redirect to home page

if ( is_user_logged_in() ) {

wp_redirect( get_option('home') );// redirect to home page

exit;

}

global $wpdb;

if(sanitize_text_field( $_GET['login'] ) != ''){

$login_fail_msg=sanitize_text_field( $_GET['login'] );

}

?>

<div class="tuts-login-form">

<?php if($login_fail_msg=='failed'){?>

<div class="error" align="center"><?php _e('Username or password is incorrect','');?></div>

<?php }?>

<div class="tuts-login-heading">

<?php _e("Tutorial Login Form",'');?>

</div>

<form method="post" action="<?php echo get_option('home');?>/wp-login.php" id="loginform" name="loginform" >

<div class="tuts-txt">

<label><?php _e('Login ID :','');?> </label>

<input type="text" tabindex="10" size="20" value="" class="input" id="user_login" required name="log" />

</div>

<div class="tuts-txt">

<label><?php _e('Password :','');?> </label>

<input type="password" tabindex="20" size="20" value="" class="input" id="user_pass" required name="pwd" />

</div>

<div class="tuts-btn">

<input type="submit" tabindex="100" value="Log In" class="button" id="wp-submit" name="wp-submit" />

<input type="hidden" value="<?php echo get_option('home');?>" name="redirect_to">

</div>

</form>

</div>

<?php

}

 

Failed Login Redirect to Homepage

We need to have a way of redirecting those failed logins to the front end. This can be achieved by creating a hook for failed login. This code should look something like:
//Redirecting to front end when login is failed

add_action( 'wp_login_failed', 'tuts_front_end_login_fail' ); // Hook for failed login

function tuts_front_end_login_fail( $username ) {

$referrer = $_SERVER['HTTP_REFERER'];

// if there's a valid referrer, and it's not the default log-in screen

if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {

wp_redirect( $referrer . '/?login=failed' );

exit;

}

}

Complete Code for Main Plugin File

Here is the full code that should be saved in a main filed and named tuts-login-form.php
<?php

/**

* Plugin Name: Tuts Login Form

* Plugin URI: https://njengah.com/

* Description: Tutorial login form plugin.

* Version: 1.0.0

* Author: Joe Njenga

* Author URI: https://njengah.com/

*/

define('TUTS_REGISTRATION_INCLUDE_URL', plugin_dir_url(__FILE__).'includes/');

//Adding frontend Styles from includes folder

function tuts_styl_incl(){

wp_enqueue_style('tuts_styl_css_and_js', TUTS_REGISTRATION_INCLUDE_URL."front-style.css");

wp_enqueue_script('tuts_styl_css_and_js');

}

add_action('wp_footer','tuts_styl_incl');

// function to login Shortcode

function tuts_login_shortcode( $atts ) {

//Redirecting logged users to home page

if ( is_user_logged_in() ) {

wp_redirect( get_option('home') );// redirect to home page

exit;

}

global $wpdb;

if(sanitize_text_field( $_GET['login'] ) != ''){

$login_fail_msg=sanitize_text_field( $_GET['login'] );

}

?>

<div class="tuts-login-form">

<?php if($login_fail_msg=='failed'){?>

<div class="error" align="center"><?php _e('Username or password is incorrect','');?></div>

<?php }?>

<div class="tuts-login-heading">

<?php _e("Tutorial Login Form",'');?>

</div>

<form method="post" action="<?php echo get_option('home');?>/wp-login.php" id="loginform" name="loginform" >

<div class="tuts-txt">

<label><?php _e('Login ID :','');?> </label>

<input type="text" tabindex="10" size="20" value="" class="input" id="user_login" required name="log" />

</div>

<div class="tuts-txt">

<label><?php _e('Password :','');?> </label>

<input type="password" tabindex="20" size="20" value="" class="input" id="user_pass" required name="pwd" />

</div>

<div class="tuts-btn">

<input type="submit" tabindex="100" value="Log In" class="button" id="wp-submit" name="wp-submit" />

<input type="hidden" value="<?php echo get_option('home');?>" name="redirect_to">

</div>

</form>

</div>

<?php

}

//Adding login shortcode

add_shortcode( 'tuts-login-form', 'tuts_login_shortcode' );

//Redirecting to front end ,when login is failed

add_action( 'wp_login_failed', 'tuts_front_end_login_fail' ); // Hook for failed login

function tuts_front_end_login_fail( $username ) {

$referrer = $_SERVER['HTTP_REFERER'];

// if there's a valid referrer, and it's not the default log-in screen

if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {

wp_redirect( $referrer . '/?login=failed' );

exit;

}

}

?>

     Styling the Login Form

After building this login form and its shortcode; now it is time to style it so that it looks good. We will be styling the HTML elements that were added to the section above to create the form. Here is the full code for styling this login form.

Remember to save this stylesheet as front-style.css and place it in the includes folder we created earlier on in this tutorial.
/*******************************
Tuts Form Plugin Styles
********************************/

/*
Tuts Form Wrap Styles

*/

.tuts-login-form { padding:30px; display:block; border:1px solid #ccc;font-family: arial; font-size:12px}

/*

Tuts Form Heading

*/
.tuts-login-heading {

font-family: arial;

font-weight:700;

text-transform:capitalize;

}

.tuts-login-heading {

display: block;

font-family: arial;

font-weight: 700; font-size:24px;

margin: 0 0 20px;

text-align: center;

text-transform: capitalize;
}

/*

Tuts Form Text Styles

*/
.tuts-txt {
display: block;
margin: 0 0 20px;
}
.tuts-txt:after{clear:both; display:block; overflow:hidden; content:""}
.tuts-txt > label {

float: left;

width: 180px;

}
.tuts-txt > input { border:1px solid #ccc; padding:8px 5px; width:300px; }

/*

Tuts Form Button

*/
.tuts-login-form .button {

background: #ccc none repeat scroll 0 0;

border: 1px solid #ccc;

border-radius: 0; text-transform:uppercase; font-size:15px;font-family: arial;

padding: 10px 20px;

}
.tuts-login-form .button:hover {

background: #000 none repeat scroll 0 0;

border: 1px solid #000;

border-radius: 0;

padding: 10px 20px;
}
.tuts-registration-form .error{

color:red;

margin-bottom: 18px;

}
/********* End of Tuts Stylesheet *************/

Testing 'Tuts Login Form Plugin'

After completing building this plugin, it is now time to see how it works and possibly debug if there are any errors. Add the plugin to your plugins directory wp-content/plugins or install the plugins just like any other plugin and activate it.

Get Started with WordPress Plugins – Build Your First Plugin

Create Login Page with Shortcode

Now we need to go to the Add page in WordPress and create a page that has our shortcode in the text area. The shortcode we created is [tuts-login-form], add this shortcode and create the login page.

Get Started with WordPress Plugins – Build Your First Plugin

Test Frontend Login Form

After creating this login page, you should now visit the page and ensure you are logged out before visiting this page. If you followed every step correctly, you should see the login as shown below:

Get Started with WordPress Plugins – Build Your First Plugin

Test the login form by logging in with your username and password. You should log in successfully. This plugin now allows us to create the login form on any WordPress page or post a feature that is great for a membership site. It is important you note that I am running the demo site using the Evolve theme which is one of our FREE themes you can download and use.

Conclusion

This tutorial has illustrated how you can use a plugin to achieve an objective like creating a login form using a shortcode in WordPress pages. This is the role that all plugins play, which is simply an extension of WordPress functionality to make it more robust and useful as a content management system. I hope you have followed this tutorial and successfully create the Tuts Login Form Plugin or your own version. If you have additional comments, compliments, or want to seek some clarification, please leave me a comment.