Rails file upload using Active Storage

In this tutorial, we would be learning to upload files in Rails. Rails file upload have become easier since the release of Active Storage. It allows us to handle file uploads without using any gem.

This tutorial aims to deliver the simplest way to integrate Rails file upload. We would be skipping the details on how Active Storage works in the back and focus on how to integrate it correctly.

If you are already on an existing project and has a model that already has a CRUD operation then you may skip to Step 3.

Step 1: Create a new Rails project.

In your terminal run the following commands.

rails new file-upload
cd file-upload

This will simply create a new Rails project and change our current directory in the newly created project.

Step 2: Create a CRUD.

Since our focus is on file upload, we would be using scaffold to create our CRUD operations.

Scaffolding requires the following command in the terminal.

rails g scaffold post title:string content:text

This will create a Post model with a title and content columns, a database migration, and all views.

Step 3: Install Active Storage.

You need to run the following command in the terminal.

rails active_storage:install
rake db:migrate

The command creates a database migration that hold the necessary data and makes file uploading possible. Since we have a new database migration, we would need to migrate it.

Step 4: Add the necessary association.

In the file app/models/post.rb add the following association.

class Post < ApplicationRecord

  has_one_attached :image

end

This will tell that our model allows an attachment image. The word image is user-defined and can be changed to anything you want.

Since we are using has_one_attached, we are only expected to attach one image per record. If you want to attach many files in a single record you may want to use has_many_attached instead.

Step 5: Add the file upload field in the form.

The scaffold the we ran in Step 2 includes the views needed in our CRUD.

In the file app/views/posts/_form.html.erb, inside the form_with, add the following.

<div class="field">
  <%= form.label :image %>
  <%= form.file_field :image %>
</div>

This will add a file upload field in the form.

Step 6: Process the new field in the controller.

All changes in this step will be done in the file app/controllers/posts_controller.rb.

First, we would need to whitelist the new field in the parameters. This is necessary to prevent attackers from passing malicious parameters to our controller.

def post_params
  params.require(:post).permit(:title, :content, :image)
end

Second, we would need to attach our image in the controller’s create method.

# POST /posts
# POST /posts.json
def create
  @post = Post.new(post_params)
  @post.image.attach(post_params[:image])

  respond_to do |format|
    if @post.save
      format.html { redirect_to @post, notice: 'Post was successfully created.' }
      format.json { render :show, status: :created, location: @post }
    else
      format.html { render :new }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

Notice that we just added @post.image.attach(post_params[:image]) in the create method.

Third, we also need to attach our image in the update method.

# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json
def update
  @post.image.purge
  @post.image.attach(post_params[:image])

  respond_to do |format|
    if @post.update(post_params)
      format.html { redirect_to @post, notice: 'Post was successfully updated.' }
      format.json { render :show, status: :ok, location: @post }
    else
      format.html { render :edit }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

In the update method we added @post.image.purge to ensure that the old attachments are deleted before we attach the new file. The next line after purge is the same as what we did in create method.

Step 7: Show the uploaded file in the view.

Now that we are able to attach files on our records, we would want to view them in the view right?

In your file app/views/posts/show.html.erb, add the following.

<p>
  <% if @post.image.attached? %>
    <p>
      <strong>Image:</strong>
      <br>
      <%= image_tag @post.image %>
    </p>
  <% end %>
</p>

It will check if there is a file attached and if it does it will show the file.

You may want to run your app using rails s and navigate to http://localhost:3000/posts to confirm that everything works.

That’s it, we have now implemented a Rails file upload using Active Storage. Take note that all files will be saved on your local disk, you can also change this but that would be for another tutorial as this aims to deliver the most basic Rails file upload.

How to create basic authentication in Ruby on Rails

In this tutorial, we will be creating a basic authentication in Ruby on Rails.

Step 1: Adding a password_digest field to the model.

This field will be used for authenticating the user.

Step 1.1-A: Coming from a fresh Rails project.

If you are doing this from a fresh project then you must first create a User model by running rails g model User in the terminal.

This will create a file in db/migrate/xxxxx_create_users.rb where xxxxx is the current date and time you ran the command.

In that file add the following:

class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      t.string :username
      t.string :password_digest
      t.timestamps
    end
  end
end

Return to your terminal and run:

rake db:migrate

This will create a users table in the database with columns username and password digest.

Step 1.1-B: Coming from an existing Rails project.

If you are doing this from an existing project then you must add password_digest field to your existing model.

In this tutorial, we will be using User as the model. Feel free to change it on your preference.

Run the following command in the terminal:

rails g migration add_password_digest_to_users

This will create a file in db/migrate/xxxxx_add_password_digest_to_users.rb

In that file add the following:

class AddPasswordDigestToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :password_digest, :string
  end
end

Return to your terminal and run:

rake db:migrate

This will add a string column password_digest to your users table in the database.

Note:

In this step, you may notice that ActiveRecord::Migration[5.2] has 5.2 in it, you must change it to the correct version, otherwise, this might not work.

You might want to check your Rails version by running the following command in the terminal:

rails -v

This tutorial is created using Rails 5.2.3.

Step 2: Creating routes for the app.

Open config/routes.rb in your text editor.

In this file, we will define the links in our app. For this tutorial, we will be creating six (6) routes. one (1) that needs authentication and five (5) unauthenticated routes.

Rails.application.routes.draw do

  # AUTHENTICATED ROUTES
  get '/dashboard' => 'dashboard#index' # THIS WILL BE THE DASHBOARD OF THE USER

  # UNAUTHENTICATED ROUTES
  get '/sign-up' => 'users#new' # THIS IS WHERE THE USER WILL REGISTER
  post '/save-user' => 'users#create' # THIS WILL BE THE PROCESS OF REGISTERING THE USER

  get '/' => 'sessions#new' # THIS IS WHERETHE USER WILL SIGN IN
  post '/' => 'sessions#create' # THIS WILL BE THE PROCESS OF SIGNING IN THE USER
  delete '/sign-out' => 'sessions#destroy' # THIS WILL BE THE PROCESS OF SIGNING OUT THE USER

end

Step 3: Creating controllers for the routes.

At this point, our app will raise an error because the routes we defined doesn’t have a matching controller.

We can see that we used three (3) different controllers in Step 2. These are the dashboard, users, and sessions.

To create a matching controller for these routes you can run the following command in the terminal. One (1) at a time.

rails g controller dashboard
rails g controller users
rails g controller sessions

This will create files in app/controllers directory.

In the dashboard controller app/controllers/dashboard_controller.rb add the following method:

def index
end

In the users controller app/controllers/users_controller.rb add the following method:

def new
end

def create
end

In the sessions controller app/controllers/sessions_controller.rb add the following method:

def new
end

def create
end

def destroy
end

If you observe the routes, it does not only matches to the controller but also matches to the methods in that controller.

The creation of method above ensures that our controller matches our routes.

Step 4: Creating the dashboard page.

In the app/views/dashboard/index.html.erb paste the following code (create the file if it does not exists):

DASHBOARD

This page will simply return a text DASHBOARD when /dashboard is accessed in the browser.

Step 5: Creating a sign up page.

From the steps above, we know that the users controller handles these processes.

In your app/controllers/users_controller.rb, inside the new method, add the following:

@user = User.new

In the app/views/users/new.html.erb paste the following code (create the file if it does not exists):

<h1>Sign Up</h1>

<%= form_with :model => @user, :url => '/save-user' do |f| %>
  <%= f.label :username %>
  <br>
  <%= f.text_field :username %>
  <br>
  <br>
  <%= f.label :password %>
  <br>
  <%= f.password_field :password %>
  <br>
  <br>
  <%= f.label :password_confirmation %>
  <br>
  <%= f.password_field :password_confirmation %>
  <br>
  <br>
  <%= f.submit %>
<% end %>

This will show an HTML form when we access the link /sign-up in our browser that will make a POST request to /save-user when submitted.

Now, we are going to edit the method that will handle the data from our form.

In the same controller file add the following method:

private

def user_params
  params.require(:user).permit :username, :password, :password_confirmation
end

This is to let to know that our app only permits username, password, and password_confirmation which is coming from our form to prevent malicious parameters to be processed.

In the create method add the following code:

@user = User.new user_params

if @user.save
  session[:user_id] = @user.id

  redirect_to '/dashboard'
else
  redirect_to '/sign-up'
end

Basically, we are just creating a new instance of User and its parameters.

If it was saved successfully then we will set the newly registered user to be the current user and redirect it the dashboard but returns back to sign up page if the registration fails.

Step 6: Creating the sign in page.

In the app/views/sessions/new.html.erb paste the following code (create the file if it does not exists):

<h1>Sign In</h1>

<%= form_with :url => '/' do |f| %>
  <%= f.label :username %>
  <br>
  <%= f.text_field :username %>
  <br>
  <br>
  <%= f.label :password %>
  <br>
  <%= f.password_field :password %>
  <br>
  <br>
  <%= f.submit %>
<% end %>

Now that we created the form, we now have to authenticate the credentials if it matches a record in the database.

In your app/controllers/sessions_controller.rb, inside the create method, add the following:

@user = User.find_by :username => params[:username]

if @user && @user.authenticate(params[:password])
  session[:user_id] = @user.id

  redirect_to '/dashboard'
else
  redirect_to '/'
end

What the code does is that it finds the user with the supplied username and authenticates its password.

It sets the session and redirects to the dashboard if it succeeds then redirects back it to the sign in page if it doesn’t.

Step 7: Creating the sign out function.

In your app/controllers/sessions_controller.rb, inside the destroy method, add the following:

session[:user_id] = nil

redirect_to '/'

We are just going to set the session[:user_id] that we defined in the sign up and sign in back to its original value which is nil and redirects back the user to the sign in page.

Step 8: Creating the helper methods.

In your app/controllers/application_controller.rb, add the following:

helper_method :current_user



def current_user
  @current_user ||= User.find_by :id => session[:user_id]
end

def authorize
  redirect_to '/' unless current_user
end

A helper method is a method that we can access in our views. The helper method current user holds the data of the currently authenticated user.

The authorize method is a method that we can call to our routes that needs a user to be authenticated before allowing access to a resource.

In this case, we defined /dashboard to be the only route that needs authentication before being accessed.

In your app/controllers/dashboard_controller.rb, add the following:

class DashboardController < ApplicationController

  def index
    authorize

    # YOUR OTHER CODE HERE
  end

end

This simply calls authorize method and redirects back to the user to the sign in page if no user is authenticated.

If you want the whole controller to be authenticated instead:

class DashboardController < ApplicationController

  before_action :authorize



  def index
  end

  def method1
  end

  def method2
  end

end

This will authenticate not just the index method but also method1 and method2.

Step 9: Adding the links in the view.

We created all this routes, pages, and stuff but we didn’t have links to access this pages at all without manually typing the links in the browser.

In your app/views/layouts/application.html.erb, add the following inside the <body> above the <%= yield %>:

<% if current_user %>
  Hi <%= current_user.username %>! | <%= link_to 'Sign Out', '/sign-out', :method => :delete %>
<% else %>
  <%= link_to 'Sign In', '/' %> | <%= link_to 'Sign Up', '/sign-up' %>
<% end %>
<br>
<br>

What it does is printing the name of user and a sign out link if it’s authenticated and sign in and sign up links if it’s unauthenticated.

Step 10: Installing bcrypt gem.

Our app may look complete at this point, but if you run it at this state, you will just encounter a lot of errors because we are lacking the core function of this tutorial.

In your Gemfile uncomment the following:

gem 'bcrypt', '~> 3.1.7'

But if it does not exists, add it instead.

In your terminal run:

bundle install

In your app/models/user.rbadd the following:

class User < ApplicationRecord

  has_secure_password

end

Step 11: Run the app.

In your terminal run:

rails s

You should be able to see the sign in page as your startup page if you access http://localhost:3000/ in your browser.

That’s it. This is just a basic authentication in Rails for learning purposes.

How to convert HTML to PDF in PHP

How to convert HTML to PDF in PHP

In this tutorial, we will be learning on how to convert HTML to PDF in PHP.

There are many PHP libraries around the internet nowadays but most of them just don’t work like you expected it to be. I have been required by my client to automatically generate documents in pdf format. I have tried many PHP pdf libraries and this library really makes it possible.

Step 1: Create the HTML file.

This static HTML file will be converted to pdf. You may use all HTML tags that you know combined with CSS.

This is somehow WYSIWYG like process, where the look of the output in your HTML file will also be the look when it was converted to pdf.

In this example, I will just create a simple invoice document. We will name the file as file.html and the content as follows.

<html>
<head>
  <style>
    html, body {
      margin: 0;
      padding: 0;
      font-family: Times New Roman;
    }
  </style>
</head>
<body>
  <table cellpadding="10" cellspacing="0" width="100%">
    <tr style="background-color: #333; color: #fff;">
      <td align="center">
        <img src="https://placehold.it/450x150&text=YOUR%20LOGO"><br><br><b>1234 Central Avenue, Ermita, Manila</b>
      </td>
    </tr>
    <tr>
      <td>
        <h1>INVOICE #4321</h1>
        April 14, 2050<br><br>
        <b>Bill To:</b><br>
        John Smith<br>
        Beehive Co.<br>
        Beehive Building, 1226 South Avenue<br>
        Manila, 1000<br>
        +63 (917) 543-2109<br>
        [email protected]
      </td>
    </tr>
  </table>
  <br><br>
  <table cellpadding="10" cellspacing="0" width="100%">
    <tr>
      <th width="80%" style="background-color: #333; color: #fff; border: 1px solid #000;">DESCRIPTION</th>
      <th width="20%" style="background-color: #333; color: #fff; border: 1px solid #000;">AMOUNT</th>
    </tr>
    <tr>
      <td width="80%" style="border: 1px solid #000;">Sample Item 1</td>
      <td width="20%" style="border: 1px solid #000;" align="right">100,000.00 PHP</td>
    </tr>
    <tr>
      <td width="80%" style="border: 1px solid #000;">Sample Item 2</td>
      <td width="20%" style="border: 1px solid #000;" align="right">100,000.00 PHP</td>
    </tr>
    <tr>
      <td width="80%" style="border: 1px solid #000;">Sample Item 3</td>
      <td width="20%" style="border: 1px solid #000;" align="right">100,000.00 PHP</td>
    </tr>
    <tr>
      <td width="80%" style="border: 1px solid #000;">Sample Item 4</td>
      <td width="20%" style="border: 1px solid #000;" align="right">100,000.00 PHP</td>
    </tr>
    <tr>
      <td width="80%" style="border: 1px solid #000;">Sample Item 5</td>
      <td width="20%" style="border: 1px solid #000;" align="right">100,000.00 PHP</td>
    </tr>
    <tr>
      <td width="80%" style="border: 1px solid #000;">Sample Item 6</td>
      <td width="20%" style="border: 1px solid #000;" align="right">100,000.00 PHP</td>
    </tr>
    <tr>
      <td style="border: 1px solid #000;" align="right"><b>TOTAL</b></td>
      <td style="background-color: #333; color: #fff; border: 1px solid #000;" align="right">600,000.00 PHP</td>
    </tr>
  </table>
  <br><br>
  If you have any concerns about this invoice, please contact<br>[Accounting Department, +63 (917) 543-2109, [email protected]]
</body>
</html>

This will be the output of file.html when it is opened in a browser.

The output of file.html in the browser.
Picture 1.1. The output of file.html in the browser.

Step 2: Download the TCPDF library.

You may download the TCPDF library on the following links: link1 / link2

This library will allow us to convert the HTML file that we have created into a PDF file format.

Step 3: Create a PHP script file.

This PHP file will execute the library together with the HTML file to have a PDF output.

In this example, we will name it as index.php

<?php
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->AddPage();
$html = file_get_contents('file.html');
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->lastPage();
$pdf->Output('file.pdf', 'D');

The code above will require the library in our file so that we can initialize the TCPDF class in the library.

The variable $html will hold the HTML file that we have created earlier and the library will do the rest to convert it to PDF.

The last line has two (2) parameters, the first parameter will be the filename of our PDF file while the second parameter is the action that we are going to do with the file.

There are many types of action that we can choose from for the second paramter. There are I, D, F, S, FI, FD, and E.

The I action is it will send the file inline with the browser, allowing it to be viewed in the browser without actually saving the file.

The D action means the file will be forced to be downloaded on the local machine given the filename in the first parameter.

The F action means the file will be saved on the local server that can be retrieved and downloaded later.

The S action will return the document as a string where the filename is ignored.

The FI action is the combination of F and I action. It will be both viewed in the browser and saved on the local server.

The FD action is the combination of F and D action. It will be both downloaded and saved on the local server.

The E action will return the document as a base64 mime multi-part email attachment (RFC 2045). This is used when the file is going to be attached to an email.

In this example, we will choose to download the pdf file that we are going to create.

The directory will have 1 folder and 2 files.

This is how the directory must look like.
Picture 3.1. This is how the directory must look like.

If you don’t have encountered an error when executing index.php then you must have the output as follows.

The output of file.pdf opened in Google Chrome browser.
Picture 3.2. The output of file.pdf opened in Google Chrome browser.

That’s it, we have now converted an HTML file into a PDF file format document in PHP.

How to resize an image in PHP

How to resize an image in PHP

In this tutorial, we will learn to resize an image in PHP.

Whenever you are doing something like a CMS for your website that requires an image to be uploaded then you can have a problem where users upload images in different dimensions.

This can be a problem in the front-end as your design will not be the same for all.

This is why we need to learn to resize an image in PHP. As long as the file is on the server then you can use this method to resize your images.

This can also be used to resize an image on upload meaning after uploading the original image it will automatically be resized after uploading.

Step 1: Get a copy of this PHP function.

<?php
function resizeImage($filename, $newwidth, $newheight) {
  list($width, $height) = getimagesize($filename);

  if (pathinfo($filename, PATHINFO_EXTENSION) == 'jpg' || pathinfo($filename,PATHINFO_EXTENSION) == 'jpeg') {
    $src = imagecreatefromjpeg($filename);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagejpeg($dst, $filename, 100);
  }

  if (pathinfo($filename,PATHINFO_EXTENSION) == 'png') {
    $src = imagecreatefrompng($filename);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagepng($dst, $filename, 0);
  }

  if (pathinfo($filename,PATHINFO_EXTENSION) == 'gif') {
    $src = imagecreatefromgif($filename);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagegif($dst, $filename, 100);
  }
}

The PHP function accepts three (3) parameters. The first parameter is a string which has the filename of the image that is going to be resized. The second parameter is an integer, this will be the new width of your image. The third and last parameter is also an integer, this will be the new height of your image.

Step 2: Use the PHP function.

Our sample image laptop.jpg having a dimension of 1920x1280.
Picture 2.1. Our sample image laptop.jpg having a dimension of 1920×1280.

In this example, we are going to have an image laptop.jpg which has a dimension of 1920×1280 and we will want to downscale this image to the quarter of its original size (480×320).

Now, the second file that we are going to have is resize.php that contains the function above and this file will also make the resizing possible.

Since the filename of our sample image is laptop.jpg and it is also in the same directory then we can use the function as follows.

resize_image('laptop.jpg', 480, 320);

After executing the file resize.php we can see now that our image has lesser file size and has a lower dimension.

Our sample image laptop.jpg having a new dimension of 480x320.
Picture 2.2. Our sample image laptop.jpg having a new dimension of 480×320.

That’s it, we have now successfully resized an image in PHP.

You may notice that whenever you use PHP file upload, the file will be uploaded to the server. After a successful upload, just call the function after the file has been uploaded for it to be resized.

Converting timestamp to time ago in PHP like Facebook

Converting timestamp to time ago in PHP like Facebook

In this tutorial, we will be learning on how to convert timestamp to time ago in PHP.

Most of you have noticed that the famous social networking site Facebook uses the time ago instead of posting the original timestamp.

Time ago is calculated based on the difference between the current time and date to the actual post time and date.

We will use a PHP function that has a parameter that accepts a timestamp it will return it in time ago format based on your server time.

Step 1: Get a copy of the following PHP function.

<?php
function timeago($datetime, $full = false) {
  date_default_timezone_set('Asia/Manila');
  $now = new DateTime;
  $ago = new DateTime($datetime);
  $diff = $now->diff($ago);
  $diff->w = floor($diff->d / 7);
  $diff->d -= $diff->w * 7;
  $string = array(
    'y' => 'yr',
    'm' => 'mon',
    'w' => 'week',
    'd' => 'day',
    'h' => 'hr',
    'i' => 'min',
    's' => 'sec',
  );

  foreach ($string as $k => &$v) {
    if ($diff->$k) {
      $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
    } 
    else {
      unset($string[$k]);
    }
  }

  if (!$full) {
    $string = array_slice($string, 0, 1);
  }
  
  return $string ? implode(', ', $string) . '' : 'just now';
}

The original source of the PHP function can be found on this thread. It is answered by Glavić on September 3, 2013.

The PHP function accepts any supported date and time format. It does not only return the time ago but also gave you the privilege to return the full exact time ago. You will understand this in the later part.

Step 2: Use the PHP function.

You will be able to use the function by calling the function name. This function can either accept one (1) or two (2) parameters where the first parameter must be a valid timestamp/datetime and the second one is a boolean(true/false).

Using the true on the boolean parameter makes it return the whole time ago.

Assuming that the current time and date is exactly 2018-04-13 11:46:58

echo timeago("2018-02-12 02:07:42"); //2 mons
echo timeago("2018-03-12 02:07:42",true); //2 mons, 1 day, 17 hrs, 39 mins, 16 secs

That’s it if you want to change the suffixes of the numbers you can do so by editing them in the $string variable in the function above.

Don’t forget to add the word ago if you really need it.

How to display number of post views WordPress

How to display number of post views WordPress

In this tutorial, we would be learning on how to display number of post views WordPress using a WordPress plugin.

Tracking the views of your post and see them growing can be a satisfaction for the writer. This is why we are going to use a WordPress plugin to show the unique view count in the front-end.

It will also include an option to sort your posts based on the view count.

Step 1: Install the Posts Unique View Counter.

Login to your WordPress admin.

Hover to Plugins in the sidebar menu then click Add New.

On the search box that can be found on the upper right corner of the screen type the keyword Posts Unique View Counter or David Angulo.

Installing the Posts Unique View Counter Plugin by David Angulo
Picture 1.1. Installing the Posts Unique View Counter plugin by David Angulo

Step 2: Activate the Posts Unique View Counter plugin.

On the sidebar menu, click Plugins to see the list of installed plugins. Simply find the Posts Unique View Counter plugin then click Activate.

Activating the Posts Unique View Counter plugin by David Angulo
Picture 2.1. Activating the Posts Unique View Counter plugin by David Angulo

Step 3: View your WordPress post list.

All view count will start at nothing. You can view the posts list by hovering to Posts in the sidebar menu then click All Posts.

You can see an additional column entitled Views that is sortable.

The count will start once a user views your post.

A sortable view count column in WordPress posts list.
Picture 3.1. A sortable view count column in WordPress posts list.

Step 4: View one of your post.

You can also view one of your posts and see just before the content the current view count of your post.

The plugin shows the view count in the front-end of the post.
Picture 4.1. The plugin shows the view count in the front-end of the post.

That’s it. This plugin only counts the unique view meaning a person that viewed the same post twice will only be counted as one.

How to display the last updated date of your posts in WordPress

How to display the last updated date of your posts in WordPress

In this tutorial, we would be learning on how to display the last updated date of your posts in WordPress.

Showing the last updated date of a post can be very beneficial. This allows your users to know that your post is still valid today, meaning it is kept up-to-date.

Some posts really need to be updated especially when you are writing tutorials because it might work today and might not work tomorrow so you’ll have to keep it updated to make sure that the post doesn’t go to waste.

Step 1: Install the Post Updated Date plugin.

Login to your WordPress admin then hover to Plugins in the sidebar menu and click Add New.

On the upper right there is a search box and type Post Updated Date. The plugin you are going to install must be authored by Ataul Ghani.

installing the post updated date plugin
Picture 1.1. Installing the Post Updated Date plugin.

Step 2: Activate the Post Updated Date plugin.

Click again the Plugins in the sidebar menu and you should see Post Updated Date in the list if you have successfully installed the plugin.

Just simply click the Activate button if the plugin isn’t yet activated.

activating the post updated date plugin
Picture 2.1. Activating the Post Updated Date plugin.

Step 3: View your post.

Hover to Posts in the sidebar menu then click All Posts.

On the list, hover to the title column then click View.

last updated date and published date
Picture 3.1. The plugin shows both published and last updated date on WordPress with Twenty Seventeen theme.

That’s it, you have now successfully shown the last updated date of your post.

Create plugin in WordPress

Create plugin in WordPress step by step tutorial for beginners

This tutorial will guide you on how to create plugin in WordPress.

WordPress plugins are simply PHP scripts that extend the functionality of your WordPress website. If you have a running WordPress website and you need to add some functionality you can always rely on the wordpress plugin directory, this enables you to add functionality to your website without the need to learn on how to code.

But, what if the functionality that you are looking for is not available? If you are a developer, then you need to write the code yourself and if you are generous enough you will make the plugin flexible, meaning it can be installed and it is compatible with all WordPress websites. If you are non-developer then you might need to hire a developer to do it for you or instead search for an alternative plugin that suits your needs.

Step 1: Create a folder.

You will need to create a folder with the folder name as your plugin name. Then put this folder in the wp-content/plugins directory.

In this tutorial, we will name the folder as mysuperbplugin.

Step 2: Create a PHP file.

The PHP file must be inside the folder that you have created and for this tutorial, we will name it as mysuperbplugin.php.

The content of mysuperbplugin.php is as follows:

<?php
/*
Plugin Name: My Superb Plugin
Plugin URI: http://www.davidangulo.xyz/portfolio/
Description: A very superb plugin.
Version: 1.0.0
Author: David Angulo
Author URI: http://www.davidangulo.xyz/
License: GPL2
*/

The content above will be the description of your plugin. This is a standard format and you can add more information if you want.

If you navigate to your plugins, you should see My Superb Plugin in the list. You might want to activate your plugin now even though it does not have any function just yet.

Step 3: Plan your plugin functionality.

Ask yourself, what should your plugin do? There are tons of plugins in the WordPress directory and if you are planning to include yours in that list you must create something unique.

Plugins can be a simple such as printing a text to complex such as having an e-commerce plugin or reservation plugin. Each plugin has their own functionalities.

I will just list some functionalities and example plugins that can guide you on how to create plugin in WordPress.

a. Admin Page

create an admin page
a. An admin page.

Most of the big plugins use this functionality. Since their plugins offer a wide range of options and configurations they will need to create a user interface for users to easily use their plugin.

A plugin that uses an Admin Page is Simple Author Box.

(Read: How to create an admin page for your WordPress plugin)

b. Sub-menu Page

submenu
b. A sub-menu page.

If one page is not enough then you need to add more pages for your plugin. This will add a child menu on the Admin page.

A plugin that uses Sub-menu Page is Yoast SEO.

(Read: How to add submenu in WordPress custom plugin)

c. Settings Page

How to create a settings page for your WordPress plugin
c. A settings page.

Some plugin needs to be configured to the settings to let the users pick the functions that they want to enable and disable. The settings page allows your plugin to save settings in the WordPress that you can use.

A plugin that uses Settings Page is WP Mail SMTP.

(Read: How to create a settings page for your WordPress plugin)

d. Dashboard Widget

How to create a dashboard widget in WordPress
d. A dashboard widget.

Dashboard widgets are the content that you see in WordPress admin dashboard. This is the first page that an admin will see whenever he login. This is a good functionality used for a summary of reports.

A plugin that uses Dashboard Widget is Wordfence.

(Read: How to create a dashboard widget in WordPress)

e. Shortcode

e. A login form shortcode.

A shortcode is a text that you can use in WordPress WYSIWYG editor to show some functionality. An example is when you have created a form using HTML, you can register it using the shortcode and this shortcode will be used in the editor for the form that you have created to appear.

A plugin that uses Shortcode is Separate Login Form.

(Read: How to create custom WordPress shortcode plugin from scratch)

f. Upload Files

upload files in WordPress programmatically
f. A file uploader plugin.

If you are developing a plugin that needs to upload files then you can use this functionality. All files uploaded using this uploader will be uploaded to wp-content/uploads directory.

(Read: How to upload files in WordPress programmatically)

h. Posts Custom Column

How to add custom column in WordPress post
h. A custom last modified date column.

Whenever you navigate to All Posts, you can see the list in a table. If you are developing a plugin that is specific for posts, then you can add a custom column generated by your plugin. Maybe you want to create a plugin that allows users to rate each post and the summary will be listed in the custom column.

A plugin that uses Posts Custom Column is Posts Unique View Counter.

(Read: How to add custom column in WordPress post)

i. Custom Database Tables

Sometimes, your plugin just needs a database to store its data. This will allow your plugin to automatically creates database tables when activated where the tables you have created can be used to perform database operations.

A plugin that uses Custom Database Tables is Caldera Forms.

(Read: How to create database tables when your plugin is activated)

j. Cron Jobs

Cron jobs are actions that are automatically executed every a specific interval. If you are creating that needs to do something automatically then you this functionality will fit your plugin.

The WordPress itself uses cron jobs.

A plugin that uses Cron Jobs is WP Crontrol.

(Read: How to create  cron job in WordPress)

So have you got any idea of what your plugin needs to do? You can always refer to look for a non-existent plugin and create them or innovate some plugins that need have additional functionalities.

Here are some plugins that have a step by step tutorial for beginners.

a. CRUD Operations Plugin (Step by Step tutorial)

This is a simple plugin that can do crud(create/read/update/delete) operations. You can refer to this tutorial to have a better understanding of WordPress database operations.

(Read: How to create CRUD operations plugin in WordPress)

b. Contact Form Plugin (Step by Step tutorial)

This is a simple plugin that allows you to put a contact form on any page/post that you want and this tutorial will guide you on how to create it.

(Read: How to create a contact form plugin in WordPress)

Step 4: Upload your plugin.

If you have successfully created your own plugin, then it is time to upload it to the WordPress plugin directory. This will allow your plugin to be open for use in public.

(Read: How to upload your plugin to WordPress plugin directory)

That’s it, I hope you are able to create plugin in WordPress.

How to create crud operations plugin in WordPress

How to create CRUD operations plugin in WordPress

In this tutorial, we would learn how to create crud operations plugin in WordPress.

This tutorial will demonstrate a WordPress plugin that can do CRUD (Create/Insert, Read/Select, Update, Delete) operations.

Since we are creating a plugin that interacts with the database you might want to read these tutorials (How to connect to WordPress database and How to insert data into WordPress database) to have a better understanding on database operations in WordPress.

Step 1: Create a database table.

We are dealing with crud database operations so we need to have database table to store be able to store data.

register_activation_hook( __FILE__, 'crudOperationsTable');

function crudOperationsTable() {
  global $wpdb;
  $charset_collate = $wpdb->get_charset_collate();
  $table_name = $wpdb->prefix . 'userstable';
  $sql = "CREATE TABLE `$table_name` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(220) DEFAULT NULL,
  `email` varchar(220) DEFAULT NULL,
  PRIMARY KEY(user_id)
  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  ";

  if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
  }
}

The register_activation_hook() function will make sure that it will automatically create a database table using the code inside the function crudOperationsTable.

The query will be a simple CREATE TABLE statement to create the database table.

You may read the detailed tutorial on How to create database tables when your plugin is activated.

Step 2: Create a page to show the table.

We will be creating a simple HTML table to show the records that we have in the database.

You can create any page you want whether a shortcode page, admin page, or even settings page but in this tutorial we would just be using an admin page.

add_action('admin_menu', 'addAdminPageContent');

function addAdminPageContent() {
  add_menu_page('CRUD', 'CRUD', 'manage_options', __FILE__, 'crudAdminPage', 'dashicons-wordpress');
}

function crudAdminPage() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'userstable';
}

The add_action together with add_menu_page() will hook our function to WordPress so that we can use this function to write our own code.

We will write the code inside the crudAdminPage() function. In this example, we already have added two lines of code that we need to interact with the database.

Step 3: Create an HTML table.

<div class="wrap">
  <h2>CRUD Operations</h2>
  <table class="wp-list-table widefat striped">
    <thead>
      <tr>
        <th width="25%">User ID</th>
        <th width="25%">Name</th>
        <th width="25%">Email Address</th>
        <th width="25%">Actions</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>

We will use the default WordPress CSS classes to design our table. However, if you want to design it your own and use frameworks such as bootstrap or create your own classes would also be fine.

In our table will have a User ID, Name, Email Address and Actions column. This is almost the same as the table that we have created in the database except that it doesn’t have the actions column.

Step 4: Create the create/insert function.

Before we can populate the HTML table, we need to have data in the database so we would be needing to create or insert data first.

Inside the <tbody></tbody> tag, we will just create a row for our insert form.

<form action="" method="post">
  <tr>
    <td><input type="text" value="AUTO_GENERATED" disabled></td>
    <td><input type="text" id="newname" name="newname"></td>
    <td><input type="text" id="newemail" name="newemail"></td>
    <td><button id="newsubmit" name="newsubmit" type="submit">INSERT</button></td>
  </tr>
</form>

We will keep the form action to blank since we will use the same page to process the data.

Now, let’s add the PHP code to process the form data. Keep also in mind that we have used the method post in our form.

if (isset($_POST['newsubmit'])) {
  $name = $_POST['newname'];
  $email = $_POST['newemail'];

  $wpdb->query("INSERT INTO $table_name(name,email) VALUES('$name','$email')");
  
  echo "<script>location.replace('admin.php?page=crud.php');</script>";
}

We just created a block of code that will only be executed when our insert form in Step 4 is submitted.

To insert the data, we will just use the INSERT INTO statement and it will be executed with the use of $wpdb->query() function.

The last line of code will just make sure that it automatically reloads the page so we can see the newly added record on our table.

Step 5: Populate the HTML table.

Now that we have created an insert function, we can now populate the database with records. Before you proceed make sure that you have atleast one (1) record to see the result of this step.

<?php
  $result = $wpdb->get_results("SELECT * FROM $table_name");
  
  foreach ($result as $print) {
    echo "
      <tr>
        <td width='25%'>$print->user_id</td>
        <td width='25%'>$print->name</td>
        <td width='25%'>$print->email</td>
        <td width='25%'><a href='admin.php?page=crud.php&upt=$print->user_id'><button type='button'>UPDATE</button></a> <a href='admin.php?page=crud.php&del=$print->user_id'><button type='button'>DELETE</button></a></td>
      </tr>
    ";
  }
?>

We will fetch the records from the database using the $wpdb->get_results() function, this is the function that executes our select statement and returns the records as an array.

To get the array values, we have used the foreach() loop and return a row to our table for every data found in the database. The action column for each record would be update and delete.

This step would be the read/select function.

Step 6: Create the update function.

When we retrieve the data from the database, we have created two (2) buttons in the actions column. One of them is the update button that acts as an anchor tag.

This button will add the id of the record that we are going to edit.

<?php
  if (isset($_GET['upt'])) {
    $upt_id = $_GET['up'];
    $result = $wpdb->get_results("SELECT * FROM $table_name WHERE user_id='$upt_id'");
    foreach($result as $print) {
      $name = $print->name;
      $email = $print->email;
    }
    echo "
    <table class='wp-list-table widefat striped'>
      <thead>
        <tr>
          <th width='25%'>User ID</th>
          <th width='25%'>Name</th>
          <th width='25%'>Email Address</th>
          <th width='25%'>Actions</th>
        </tr>
      </thead>
      <tbody>
        <form action='' method='post'>
          <tr>
            <td width='25%'>$print->user_id <input type='hidden' id='uptid' name='uptid' value='$print->user_id'></td>
            <td width='25%'><input type='text' id='uptname' name='uptname' value='$print->name'></td>
            <td width='25%'><input type='text' id='uptemail' name='uptemail' value='$print->email'></td>
            <td width='25%'><button id='uptsubmit' name='uptsubmit' type='submit'>UPDATE</button> <a href='admin.php?page=crud.php'><button type='button'>CANCEL</button></a></td>
          </tr>
        </form>
      </tbody>
    </table>";
  }
?>

We just created a condition where if the user_id to be edited is available then we would show a table containing the record we are going to edit.

Just like in the insert function, this will just be a form but the only difference is that it already contains the previous record ready to be changed/updated.

It will have two (2) buttons, the first button will be the confirmation button that will submit the form if you want to confirm the changes and the second button which is the cancel button that will simply reload and remove the user_id from the URL.

We will also set the form action to blank and method to post.

Now, we are going to add another code to process our update form.

if (isset($_POST['uptsubmit'])) {
  $id = $_POST['uptid'];
  $name = $_POST['uptname'];
  $email = $_POST['uptemail'];

  $wpdb->query("UPDATE $table_name SET name='$name',email='$email' WHERE user_id='$id'");
  
  echo "<script>location.replace('admin.php?page=crud.php');</script>";
}

This code will only be executed if our update form is submitted.

We will also use the $wpdb->query() function to execute an UPDATE SET statement and the last line of code to also reload the page to see the results.

Step 7: Create the delete function.

Same with the update function. The delete button will also add the user_id to the URL of the record to be deleted.

if (isset($_GET['del'])) {
  $del_id = $_GET['del'];

  $wpdb->query("DELETE FROM $table_name WHERE user_id='$del_id'");
  
  echo "<script>location.replace('admin.php?page=crud.php');</script>";
}

So the condition for our delete function to be executed is when the delete button is clicked and the user_id is detected in the URL then it will execute the delete query to delete the record from the database then reloads the page to see the result.

Complete code:

<?php
/*
Plugin Name: CRUD Operations
Plugin URI: https://www.davidangulo.xyz/portfolio/
Description: A simple plugin that allows you to perform Create (INSERT), Read (SELECT), Update and Delete operations.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

register_activation_hook( __FILE__, 'crudOperationsTable');

function crudOperationsTable() {
  global $wpdb;
  $charset_collate = $wpdb->get_charset_collate();
  $table_name = $wpdb->prefix . 'userstable';
  $sql = "CREATE TABLE `$table_name` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(220) DEFAULT NULL,
  `email` varchar(220) DEFAULT NULL,
  PRIMARY KEY(user_id)
  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  ";

  if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
  }
}


add_action('admin_menu', 'addAdminPageContent');

function addAdminPageContent() {
  add_menu_page('CRUD', 'CRUD', 'manage_options' ,__FILE__, 'crudAdminPage', 'dashicons-wordpress');
}

function crudAdminPage() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'userstable';

  if (isset($_POST['newsubmit'])) {
    $name = $_POST['newname'];
    $email = $_POST['newemail'];

    $wpdb->query("INSERT INTO $table_name(name,email) VALUES('$name','$email')");

    echo "<script>location.replace('admin.php?page=crud.php');</script>";
  }

  if (isset($_POST['uptsubmit'])) {
    $id = $_POST['uptid'];
    $name = $_POST['uptname'];
    $email = $_POST['uptemail'];

    $wpdb->query("UPDATE $table_name SET name='$name',email='$email' WHERE user_id='$id'");

    echo "<script>location.replace('admin.php?page=crud.php');</script>";
  }

  if (isset($_GET['del'])) {
    $del_id = $_GET['del'];

    $wpdb->query("DELETE FROM $table_name WHERE user_id='$del_id'");

    echo "<script>location.replace('admin.php?page=crud.php');</script>";
  }
  ?>

  <div class="wrap">
    <h2>CRUD Operations</h2>
    <table class="wp-list-table widefat striped">
      <thead>
        <tr>
          <th width="25%">User ID</th>
          <th width="25%">Name</th>
          <th width="25%">Email Address</th>
          <th width="25%">Actions</th>
        </tr>
      </thead>
      <tbody>
        <form action="" method="post">
          <tr>
            <td><input type="text" value="AUTO_GENERATED" disabled></td>
            <td><input type="text" id="newname" name="newname"></td>
            <td><input type="text" id="newemail" name="newemail"></td>
            <td><button id="newsubmit" name="newsubmit" type="submit">INSERT</button></td>
          </tr>
        </form>
        <?php
          $result = $wpdb->get_results("SELECT * FROM $table_name");
          foreach ($result as $print) {
            echo "
              <tr>
                <td width='25%'>$print->user_id</td>
                <td width='25%'>$print->name</td>
                <td width='25%'>$print->email</td>
                <td width='25%'><a href='admin.php?page=crud.php&upt=$print->user_id'><button type='button'>UPDATE</button></a> <a href='admin.php?page=crud.php&del=$print->user_id'><button type='button'>DELETE</button></a></td>
              </tr>
            ";
          }
        ?>
      </tbody>  
    </table>
    <br>
    <br>
    <?php
      if (isset($_GET['upt'])) {
        $upt_id = $_GET['upt'];
        $result = $wpdb->get_results("SELECT * FROM $table_name WHERE user_id='$upt_id'");
        foreach($result as $print) {
          $name = $print->name;
          $email = $print->email;
        }
        echo "
        <table class='wp-list-table widefat striped'>
          <thead>
            <tr>
              <th width='25%'>User ID</th>
              <th width='25%'>Name</th>
              <th width='25%'>Email Address</th>
              <th width='25%'>Actions</th>
            </tr>
          </thead>
          <tbody>
            <form action='' method='post'>
              <tr>
                <td width='25%'>$print->user_id <input type='hidden' id='uptid' name='uptid' value='$print->user_id'></td>
                <td width='25%'><input type='text' id='uptname' name='uptname' value='$print->name'></td>
                <td width='25%'><input type='text' id='uptemail' name='uptemail' value='$print->email'></td>
                <td width='25%'><button id='uptsubmit' name='uptsubmit' type='submit'>UPDATE</button> <a href='admin.php?page=crud.php'><button type='button'>CANCEL</button></a></td>
              </tr>
            </form>
          </tbody>
        </table>";
      }
    ?>
  </div>
  <?php
}

That’s pretty much it. I hope you understand some basic database operations in WordPress.

How to create a contact form plugin in WordPress

How to create a contact form plugin in WordPress

In this tutorial, we would be dealing with how to create a contact form plugin in WordPress.

There are tons of contact form plugins in the WordPress plugin directory. There are also contact form included in some WordPress themes.

If you are wanting to become one of those developers in the repository then you got to start somewhere.

Also, if you are also the person who don’t want to use plugins in the directory because some of them have the functions that you don’t actually need and it just bloats your website then you can use this tutorial to create your own simple contact form plugin.

Note:

  • This will not work on localhost. (unless you have installed and correctly configured some STMP plugin such as WP Mail SMTP)

Since we want to show the form using the WordPress WYSIWYG editor then we can create it as a shortcode. You can read more on about shortcodes in how to create a shortcode tutorial.

Step 1: Create the plugin header.

Below is the plugin header that we are going to use. Feel free to edit some of the values.

<?php
/*
Plugin Name: Simple Contact Form
Plugin URI: http://www.davidangulo.xyz/portfolio/
Description: A very simple contact form.
Version: 1.0.0
Author: David Angulo
Author URI: http://www.davidangulo.xyz/
License: GPL2
*/

This will make our plugin hooked into the WordPress core.

Step 2: Create two (2) functions.

function myContactFormRender() {

}

function myContactForm() {

}

The function myContactFormRender() will render our HTML codes to make sure that it will fit in the theme.

The other function myContactForm() will have the form and the PHP code to process the form.

Step 3: Create a shortcode.

We will hook the myContactFormRender() function to be able to use it as a shortcode.

add_shortcode('simple_contact_form', 'myContactFormRender');

We will use the shortcode [simple_contact_form] to show our contact form.

Step 4: Create the fields.

We will create fields inside the function myContactForm().

<form action="<?php echo esc_url($_SERVER['REQUEST_URI']);?>" method="post">
    <label for="scf-name">Name:</label><input type="text" class="form-control" id="scf-name" name="scf-name" required>
    <label for="scf-email">Email Address:</label><input type="email" class="form-control" id="csf-email" name="scf-email" required>
    <label for="scf-subject">Subject:</label><input type="text" class="form-control" id="scf-subject" name="scf-subject" required>
    <label for="scf-message">Message:</label><textarea class="form-control" id="scf-message" name="scf-message" rows="5" required></textarea>
    <button class="pull-right" type="submit" id="scf-submit" name="scf-submit">Send</button>
</form>

In this example, we are going to have a field for the name, email address, subject and the message of the sender and all of them are required.

We also used the method post to make it more private and action to self since our shortcode also hold the code to process our form.

Step 5: Create the form processing code.

<?php
if (isset($_POST['scf-submit'])) {
  $name = $_POST['scf-name'];
  $email = $_POST['scf-email'];
  $subject = $_POST['scf-subject'];
  $message = $_POST['scf-message'];
  $to = get_option('admin_email');
  $headers = "From: $name <$email>" . "\r\n";

  if (wp_mail($to,$subject,$message,$headers)) {
    echo '<script>alert("Your message has been sent successfully.");</script>';
  }
  else {
    echo '<script>alert("An error has occured.");</script>';
  }
}

We have created a condition where our code will only process the form when the form is actually submitted.

The $to variable is assigned in a WordPress function get_option() with a parameter of admin_email. This will automatically fetch the email address of the WordPress website.

The wp_mail() function behaves likes the built-in PHP mail() function.

Then the last condition that we have created would be to check whether our contact form really sends our message or not, just for the user to be aware.

Step 6: Add CSS design.

<style>
  .form-control {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .pull-right {
    float: right;
  }
</style>

It is up to you on how you will design your contact form as this two (2) classes above are enough for me.

Take a note that most of the time, it takes the appearance of the theme installed so you don’t have to worry much designing the form.

Step 7: Connect the two functions.

function myContactFormRender() {
  ob_start();
  myContactForm();
  return ob_get_clean();
}

function myContactForm() {
  //your code in steps 4, 5, and 6
}

You may have observed that we created two (2) functions earlier, and this is the time to connect them.

Complete code:

<?php
/*
Plugin Name: Simple Contact Form
Plugin URI: https://www.davidangulo.xyz/portfolio/
Description: A very simple contact form.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

add_shortcode('simple_contact_form', 'myContactFormRender');

function myContactFormRender() {
  ob_start();
  myContactForm();
  return ob_get_clean();
}

function myContactForm() {
  if (isset($_POST['scf-submit'])) {
    $name = $_POST['scf-name'];
    $email = $_POST['scf-email'];
    $subject = $_POST['scf-subject'];
    $message = $_POST['scf-message'];
    $to = get_option('admin_email');
    $headers = "From: $name <$email>" . "\r\n";

    if (wp_mail($to,$subject,$message,$headers)) {
      echo '<script>alert("Your message has been sent successfully.");</script>';
    }
    else {
      echo '<script>alert("An error has occured.");</script>';
    }
  }
  ?>
    <style>
      .form-control {
        width: 100%;
        margin-bottom: 20px;
      }
      
      .pull-right {
        float: right;
      }
    </style>
    <form action="<?php echo esc_url($_SERVER['REQUEST_URI']);?>" method="post">
      <label for="scf-name">Name:</label><input type="text" class="form-control" id="scf-name" name="scf-name" required>
      <label for="scf-email">Email Address:</label><input type="email" class="form-control" id="csf-email" name="scf-email" required>
      <label for="scf-subject">Subject:</label><input type="text" class="form-control" id="scf-subject" name="scf-subject" required>
      <label for="scf-message">Message:</label><textarea class="form-control" id="scf-message" name="scf-message" rows="5" required></textarea>
      <button class="pull-right" type="submit" id="scf-submit" name="scf-submit">Send</button>
    </form>
  <?php
}

That’s it, our simple contact form plugin is done. Just activate the plugin that we have created and just simply use the shortcode [simple_contact_form] then click Publish.

Happy developing!