Posts

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.

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.