Posts

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 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.

insert data into WordPress database

How to insert data into WordPress database

To insert data into WordPress database, we have learned that you need to connect the database. If you don’t know how you can refer to the previous topic entitled How to connect to WordPress database.

After a successful connection to the database, we should start by populating it with data. We will once again use the $wpdb object to make modifications in the database.

In the previous topic, we left at having the following code:

function myFunction() {     
  global $wpdb; 
} 

The code above is needed to make a connection to the database.

Using the $wpdb->insert()

WordPress has another way of inserting into the database. This is not your usual using of INSERT INTO statement.

The basic syntax for inserting data to WordPress database is <?php $wpdb->insert($table_name, $data); ?>. The $table_name is a string that is the name of the database table to insert data into. On the other hand, $data is an array that will be inserted into the database table.

Now we have learned the basic syntax for the WordPress insert, we should have a code like this:

function myFunction() {     
  global $wpdb;     
  $table_name = $wpdb->prefix . 'my_table';     

  $wpdb->insert($table_name, array('column_1' => $data_1, 'column_2' => $data_2, //other columns and data (if available) ...)); 
} 

For example, I have a table named wp_myExampleTable that looks like this:

insert data to WordPress database
Figure 1. Newly created table named “wp_myExampleTable“.

content_id is the primary key which has a type of integer with auto increment.
content_message is a varchar type that has a length of 200.
content_date has a type of datetime.

I will try to insert some data into wp_myExampleTable using the code below:

function myFunction() {     
  global $wpdb;     
  $table_name = $wpdb->prefix . 'myExampleTable';     
  $message = 'Insert to database tutorial.';     
  $date = date('Y-m-d H:i:s');     
  $wpdb->insert($table_name, array('content_id' => NULL, 'content_message' => $message, 'content_date' => $date)); 
} 

If the code runs without any error then the data is successfully inserted into the database. The table wp_myExampleTableshould now look like this:

insert data to WordPress database
Figure 2. wp_myExampleTable after running the script.

Assuming that we run this script at exactly December 19, 2017 at 1:00 in the afternoon.

Using the $wpdb->query()

I personally use this method to insert since I am familiar with SQL queries. This method can be used in executing any SQL queries. So if you are familiar or more comfortable in using SQL queries then this would fit you more.

The basic syntax for this method would be <?php  $wpdb->query($query); ?>. $query is a string variable that holds the SQL query to execute. For this example, we would be using the INSERT INTO statement.

If we are going to insert another data in the wp_myExampleTable table then we should run the code below:

function mySecondFunction() {     
  global $wpdb;     
  $table_name = $wpdb->prefix . 'myExampleTable';     
  $message = 'Another method of insert.';     
  $date = date('Y-m-d H:i:s');     
  $wpdb->query("INSERT INTO $table_name(content_id, content_message, content_date) VALUES(NULL, '$message', '$date')"); 
} 
insert data to WordPress database
Figure 3. wp_myExampleTable after using the other method.

The database table should look like this if we successfully inserted the new data.

Assuming that we run the script at exactly after five (5) minutes.

That’s it. I hope you learned something.

connect to WordPress database

How to connect to WordPress database

Connect to WordPress database using PHP and MySQL. In PHP you can connect and modify databases in which MySQL is the most popular database system for this.

Database tables holds the data found in your website. Tables are collection of related data that consists of columns and rows. For you to be able to modify these data, you need to connect to the database. There are many ways to connect to the database and WordPress made it easier.

THE WPDB CLASS & WPDB OBJECT

Unlike in writing PHP code from scratch where you need to properly configure your database connection, WordPress provides a class called wpdb that is created upon successful installation of WordPress. This class is defined in www.yourdomain.com/wp-includes/wp-db.php.

Its primary purpose is to provide all functions needed to communicate with WordPress database.

You don’t use the wpdb class to your codes instead WordPress provides an object called $wpdb that came from wpdb class. Making a connection to the database was the primary purpose of this object.

Now, to make a connection to the database in your WordPress PHP code, you need to declare $wpdb as a global variable by using the global keyword.

You will now have a PHP code like this:

function myFunction() {     
  global $wpdb; 
} 

That’s it! You successfully connected to the WordPress database. From this point, you should be able to use all database functions of WordPress.

Database tables generated by WordPress is not the only tables that $wpdb can modify. It also includes the other tables generated by other means such as installing custom plugins and creating some yourselves manually.