Posts

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!

How to create database tables when your plugin is activated

How to create database tables when your plugin is activated

In this tutorial, we would be learning on how to create database tables when your plugin is activated.

If you are developing your own WordPress plugin, chances are there are some data you need to save to keep your plugin running. Sometimes it can be inputs or some configurations on your plugin.

It is recommended that you create a separate database table if you need to store data for your plugin.

Step 1: Hook a function when the plugin is activated.

register_activation_hook( __FILE__, 'myPluginCreateTable');

function myPluginCreateTable() {

}

In this example, the function would be myPluginCreateTable and it is hooked by register_activation_hook(). The use of register_activation_hook() function is that it is executed when the plugin is activated.

When our plugin is activated it will execute the function myPluginCreateTable().

Step 2: Write the code for creating tables.

The code will be written inside the function that we have created earlier so that it will be automatically excuted when our plugin is activated.

global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'customtable';
$sql = "CREATE TABLE `$table_name` (
`id` int(11) NOT NULL,
`column2` varchar(220) DEFAULT NULL,
`column3` varchar(220) DEFAULT NULL,
`column4` int(11) DEFAULT '1',
PRIMARY KEY(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);
}

In this process, we need to use the $wpdb object to interact with the database. You might want to read How to connect to WordPress database.

The table name that we are going to create will be named as {your-prefix}_customtable where {your-prefix} is depending on the prefix that you have saved during the installation process, it is commonly installed as wp_.

In order to make it more flexible, we will just fetch your own prefix using the $wpdb->prefix so that it will automatically adjust to whatever you have used during the installation.

The $sql variable will hold the query to be executed. Make sure that you write a valid create table query to make this work.

The next line would be a condition, it will only create the table if the table that we are creating is non-existent since we want to avoid the scenario when our plugin is deactivated and activated again as it will execute the create table twice.

We need to require the upgrade.php as this file makes it possible to upgrade the database. We are using the dbDelta() function that can be found also in upgrade.php.

Complete Code:

<?php
/*
Plugin Name: Create database table
Plugin URI: https://www.davidangulo.xyz/portfolio/
Description: A simple WordPress plugin that creates a database table on activation.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

register_activation_hook( __FILE__, 'myPluginCreateTable');

function myPluginCreateTable() {
  global $wpdb;
  $charset_collate = $wpdb->get_charset_collate();
  $table_name = $wpdb->prefix . 'customtable';
  $sql = "CREATE TABLE `$table_name` (
  `id` int(11) NOT NULL,
  `column2` varchar(220) DEFAULT NULL,
  `column3` varchar(220) DEFAULT NULL,
  `column4` int(11) DEFAULT '1',
  PRIMARY KEY(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);
  }
}

That’s it. When your plugin is activated, it will automatically create a database table that you can use for your data.

In any case, you need help in populating your database tables I would recommend reading How to insert data into WordPress database.

How to add custom column in WordPress post

How to add custom column in WordPress post

In this tutorial, we would be learning on how to add custom column in WordPress post.

If you are creating a plugin that is meant to be used on posts, then you might need this function.

You might have noticed that there are six (6) default columns in the WordPress posts table.

The goal of this tutorial is to add another column that will show the date when the post was last modified.

Step 1: Setup the column header.

This will show the name that will appear as the header in the table. It will also hook our function to WordPress.

add_filter('manage_posts_columns', 'column_head');

function column_head($columns) {
  $columns['custom_column'] = 'Last Modified Date';
  return $columns;
}

In this example, we would be naming our custom column as Last Modified Date.

Step 2: Setup the column content.

Now that we have the header, we must put something in the table data. It can be anything you want.

add_action('manage_posts_custom_column', 'column_content', 10, 2);

function column_content($column_name, $post_ID) {
  if ($column_name == 'custom_column') {
    echo 'Last Modified<br><abbr title=' . get_the_modified_time('Y/m/d') . get_the_modified_time('h:i:s a') . '>' . get_the_modified_time('Y/m/d') . '</abbr>';
  }
}

You can even use the $post_ID variable to uniquely identify each post.

We must put the condition on where would we put the content. It must be the same on the custom column name that we have created.

If you do not do this then it will be added to all custom column available and might conflict with other plugins with the same capabilities.

In this example, we would be showing a column composed of the date when the post was last modified.

Complete Code:

<?php
/*
Plugin Name: Custom Column Plugin Example
Plugin URI: https://www.davidangulo.xyz/portfolio/
Description: Add a custom column on WordPress posts.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

add_filter('manage_posts_columns', 'column_head');

function column_head($columns) {
  $columns['custom_column'] = 'Last Modified Date';
  return $columns;
}


add_action('manage_posts_custom_column', 'column_content', 10, 2);

function column_content($column_name, $post_ID) {
  if ($column_name == 'custom_column') {
    echo 'Last Modified<br><abbr title=' . get_the_modified_time('Y/m/d') . get_the_modified_time('h:i:s a') . '>' . get_the_modified_time('Y/m/d') . '</abbr>';
  }
}

That’s it, we have now added the 7th column on the WordPress post page that shows when the post was last modified.

How to create a dashboard widget in WordPress

How to create a dashboard widget in WordPress

In this tutorial, we would be learning on how to create a dashboard widget in WordPress.

If ever that you are developing a plugin that needs a report generation then this one is the perfect tutorial for you. This tutorial will make your plugin able to show a widget in your administrator dashboard.

You can use this for many things such as sales summary if you are on e-commerce, or something like login attempts if you are on a security plugin.

Some famous plugins that use a dashboard widget are Yoast SEO and Wordfence.

Step 1: Setup the hook for your dashboard widget.

add_action('wp_dashboard_setup', 'registerDashboardWidget');

function registerDashboardWidget() {
  wp_add_dashboard_widget('My Widget', 'My Widget', 'myPluginDashboardWidget');
}

This step is important for WordPress to detect that we are creating a dashboard widget.

You can change My Widget, this will be the title of your dashboard widget as seen in the featured post image.

The last parameter myPluginDashboardWidget will be the function name that will hold the content for your dashboard widget.

Step 2: Create the function for the content.

Since we have declared myPluginDashboardWidget as our function name in Step 1 then we must create a function with the same name.

You can change this function name to anything you want as long as the names must be the same.

function myPluginDashboardWidget() {
  echo "<h2>Hello World!</h2><p>This is my plugin's dashboard widget.</p>";
}

In this example, we would just be print some generic text. The content of your dashboard widget will always be up to you. You can use PHP codes and HTML tags for the widget.

Complete Code:

<?php
/*
Plugin Name: Dashboard Widget Example
Plugin URI: https://www.davidangulo.xyz/portfolio/
Description: Just another WordPress plugin with dashboard widget.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

add_action('wp_dashboard_setup', 'registerDashboardWidget');

function registerDashboardWidget() { 
  wp_add_dashboard_widget('My Widget', 'My Widget', 'myPluginDashboardWidget');
}
 
function myPluginDashboardWidget() {
  echo "<h2>Hello World!</h2><p>This is my plugin's dashboard widget.</p>";
}

That’s it, just activate the plugin and navigate to your dashboard and it will show My Widget on the dashboard.

How to create a settings page for your WordPress plugin

How to create a settings page for your WordPress plugin

In this tutorial, we would be learning on how to create a settings page for your WordPress plugin.

Whether the plugin that we are creating is small or big, sometimes we just need a setting for it. It can be from asking a user to pick between yes or no, it also can be asking for a data such as a name or an email address.

This tutorial will guide you on how to do it in your WordPress plugin.

Step 1: Setup the hook for your settings page.

add_action('admin_menu', 'registerOptionPage');

function registerOptionPage() {
  add_options_page('Plugin Name', 'Plugin Name', 'manage_options', 'myPluginSettings', 'optionPageContent');
}

function optionPageContent() {

}

We need the hook to add our plugin in the settings options. This will add the Plugin Name if you hover to the settings in your admin side menu.

You can change the Plugin Name to the name of your plugin but for this example, we will just keep it as it is. The function optionPageContent() will have the content or user interface of your settings page, this includes HTML and CSS.

Step 2: Add the settings for your plugin.

<?php
function optionPageContent() {
?>
  <h2>Plugin Name</h2>
  <p>These are the settings for your plugin.</p>
  <form method="post" action="options.php">
    <?php
      settings_fields("myPluginSettings");
    ?>
    <table class="form-table">
      <tbody>
        <tr>
          <th>Setting 1</th>
          <td>
            <input type="text" name="setting1" id="setting1" value="<?php echo get_option('setting1');?>"><br><span class="description"> Enter your description for the setting 1 here.</span>
          </td>
        </tr>
        <tr>
          <th>Setting 2</th>
          <td>
            <input type="text" name="setting2" id="setting2" value="<?php echo get_option('setting2');?>"><br><span class="description"> Enter your description for the setting 2 here.</span>
          </td>
        </tr>
      </tbody>
    </table>
    <?php
      submit_button();
    ?>
</form>
<?php
}

Here are some HTML tags you are familiar with to create the user interface for your plugin settings page.

We have created a form that will be processed by options.php as this file contains all the settings in your WordPress website. This includes the default settings and some settings from your installed plugins. You can also consider this as a master list of the settings.

We also need to define the settings_field() so that WordPress will be able to identify each setting uniquely. I recommend that you use your plugin name plus the word settings in the parameter.

To view your settings you will just use the get_option() function. This is not only available for your own settings but also you can use it to retrieve settings from the default list such as admin_email. You can see all options in the options.php, where using get_option() allows you to use whatever the data you need.

Step 3: Register the plugin settings.

If you tried opening the options.php in Step 2. You will notice that our settings are still not listed there because it is not yet registered in the settings.

To register it, you need to add another hook to register the settings.

add_action('admin_init', 'registerPluginSettings');

function registerPluginSettings() {
  register_setting('myPluginSettings', 'setting1');
  register_setting('myPluginSettings', 'setting2');
}

The register_setting() function will register your settings. The first parameter is the same as settings_field() in Step 2. This is to identify where are these settings used, so in this case, it is identified that our plugin is the one registered and uses this setting. While on the second parameter is the name of the setting, make sure it matches the name and the id of the fields in Step 2.

You can retrieve your settings by using the get_option() function with your setting name as the parameter.

Complete Code:

<?php
/*
Plugin Name: WordPress plugin with settings
Plugin URI: wordpress.org/plugins
Description: Just another WordPress plugin with settings page.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

add_action('admin_menu', 'registerOptionPage');

function registerOptionPage() {
  add_options_page('Plugin Name', 'Plugin Name', 'manage_options', 'myPluginSettings', 'optionPageContent');
}


function optionPageContent() {
?>
<h2>Plugin Name</h2>
<p>These are the settings for your plugin.</p>
<form method=post" action="options.php">
  <?php
    settings_fields('myPluginSettings');
  ?>
  <table class="form-table">
    <tbody>
      <tr>
        <th>Setting 1</th>
        <td>
          <input type="text" name="setting1" id="setting1" value="<?php echo get_option('setting1');?>"><br><span class="description"> Enter your description for the setting 1 here.</span>
        </td>
      </tr>
      <tr>
        <th>Setting 2</th>
        <td>
          <input type="text" name="setting2" id="setting2" value="<?php echo get_option('setting2');?>"><br><span class="description"> Enter your description for the setting 2 here.</span>
        </td>
      </tr>                    
    </tbody>
  </table>
  <?php 
    submit_button();
  ?>
</form>
<?php
}


add_action('admin_init', 'registerPluginSettings');

function registerPluginSettings() {
  register_setting('myPluginSettings', 'setting1');
  register_setting('myPluginSettings', 'setting2');
}

That’s it, you have now added settings for your WordPress plugin.

How to create cron job in WordPress

How to create cron job in WordPress

In this tutorial, we would be learning how to create cron job in WordPress.

Sometimes you just need some automated functions in your WordPress plugins. Maybe you need to generate a report every 12 hours and you need to do this automatically, this is the function that you need to make this possible.

Did you know that wp-cron is different from the cron jobs offered by your hosting provider? Cron jobs in your hosting provider are more reliable than using wp-cron. Cron jobs execute exactly with the time you have set while in wp-cron you need someone to view your site for it to activate. But if you are at least having one (1) visit in your WordPress website then wp-cron should work.

Step 1: Setup the hook name for the action.

The hook name will be the name for your wp-cron. I’ll give you some example hook name just in case you don’t have any idea. If you are generating reports then you can name your hook name as generate_reports.

In this example we would just be using some generic hook name such as my_daily_event.

function register_schedule() { 
  if (!wp_next_scheduled('my_daily_event')) { 
    wp_schedule_event(strtotime'"06:00:00'), 'daily', 'my_daily_event'); 
  } 
}

register_activation_hook(__FILE__, 'register_schedule'); 

The use of register_activation_hook is when the plugin is activated it will add our wp-cron to the list of cron events.

In the wp_schedule_event we have used strtotime('06:00:00') and daily, this is in 24-hour format, which means our wp-cron will be executed every day at 06:00 AM.

On the first parameter, you can set any time you want and you can also use the time() function. The time() function is more reliable when creating a wp-cron that executes many times a day.

On the second parameter, you can pick from the default options from WordPress, you can select hourly (executes once per hour), twicedaily (executes every 12 hours), and daily (executes once a day). But if you want to add to add more option in these, I will show you how later.

Step 2: Create the function to be executed.

We will be creating the function that will be executed for our wp-cron.

function do_this_daily() {    
  wp_mail('[email protected]', 'Morning Message', 'Good Morning! Have a nice day. :)'); 
}

add_action('my_daily_event', 'do_this_daily'); 

In this case, our wp-cron will send a good morning email message to [email protected] every day at 06:00 AM.

Just put inside the function the codes you want to be executed automatically.

Step 3: Add a deactivation hook.

In Step 1 we have created an activation hook which executes when the plugin activates.

We need this to remove our hook when the plugin deactivates, which means it will stop from auto executing.

function remove_schedule() { 
  wp_clear_scheduled_hook('my_daily_event'); 
}

register_deactivation_hook(__FILE__, 'remove_schedule'); 

Step 4: Add a custom cron schedule.

Just incase you want to have a wp-cron that runs on a specific interval that is not available in the default options.

function custom_cron_schedules($schedules) {
  if (!isset($schedules['5minutes'])) {
    $schedules['5minutes'] = array(
      'interval' => 5*60,
      'display' => __('Once every 5 minutes'));
  }

  if (!isset($schedules['halfhour'])) {
    $schedules['halfhour'] = array(
      'interval' => 30*60,
      'display' => __('Once every 30 minutes'));
  }

  return $schedules;
}

add_filter('cron_schedules', 'custom_cron_schedules');

If we add the code above, it will add 5minutes and halfhour to the list of cron schedules. Meaning, at this point we already have five (5) cron schedules they are hourly, twicedaily, daily, 5minutes and halfhour. You can change the name to your preference and you can add more to the list.

Just take note that interval is expressed in seconds so we have to multiply the number of minutes by 60.

So if you are going to run a function every 5 minutes then you can simply just change daily to 5minutes.

Complete code:

<?php
/*
Plugin Name: My cron WordPress plugin
Plugin URI: wordpress.org/plugins
Description: A simple WordPress plugin that executes many times in a certain interval.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

register_activation_hook( __FILE__, 'register_schedule');

function register_schedule() {
  if (!wp_next_scheduled('my_daily_event')) {
    wp_schedule_event(strtotime('06:00:00'), 'daily', 'my_daily_event');
  }
}


add_action('my_daily_event', 'do_this_daily');

function do_this_daily() {
  wp_mail('[email protected]', 'Morning Message', 'Good Morning! Have a nice day. :)');
}


register_deactivation_hook( __FILE__, 'remove_schedule');

function remove_schedule() {
  wp_clear_scheduled_hook('my_daily_event');
}


add_filter('cron_schedules', 'custom_cron_schedules');

function custom_cron_schedules($schedules) {
  if (!isset($schedules['5minutes'])) {
    $schedules['5minutes'] = array(
      'interval' => 5*60,
      'display' => __('Once every 5 minutes'));
  }

  if (!isset($schedules['halfhour'])) {
    $schedules['halfhour'] = array(
      'interval' => 30*60,
      'display' => __('Once every 30 minutes'));
  }

  return $schedules;
}

Since this is a WordPress plugin, we must put this file in the plugin directory of our WordPress website.

There is a plugin that I recommend and use, it is named as WP Crontrol by John Blackbourn & contributors. It will show all the wp-cron events in detailed format which includes the hook name, the name of the function that executes, what time it executes and it even allows you to run a wp-cron manually. You can also add cron schedules without any coding.

That’s it, we have now created a wp-cron that executes automatically. I hope you have learned something.