Create a custom WordPress plugin from scratch with database tables

It’s very easy to create a WordPress plugin then you might expect. With the help of this tutorial, you can create a custom WordPress plugin from scratch with just a few lines of code.

1. Getting started

I would recommend you create a custom WordPress plugin from scratch into your local machine first. Install XAMPP if you don’t have it already in your PC and then install WordPress.

In this tutorial, I will be using the following configuration WordPress 5.3.1, Apache 2.4.41, MariaDB 10.4.10, PHP 7.3.12, phpMyAdmin 4.9.2, XAMPP Control Panel 3.2.4.

In this article, I will show you to create a plugin and create a plugin shortcode to list all the recent posts.

2. Files and folders

First of all, we need to create basic files and folder structure of the plugin. Go to the wp-content/plugins/ folder in your WordPress and create a folder with an appropriate plugin name. 

eg: wp-content/plugins/my-first-plugin 

This is the place where we will be adding all the plugin required files and assets.

Note: You cannot use space in the folder name, for name separation you use hyphens (-).

eg: my-first-plugin

create a custom WordPress plugin from scratch

3. Creating the plugin file

We must have to create the main plugin PHP file with the same name as the folder name.

In the above example, my custom plugin name is my-first-plugin so I will create my-first-plugin.php file accordingly directory named.

Copy the following custom WordPress plugin example code and paste it into your main plugin file.

<?php
/*
Plugin Name: My First Plugin
Plugin URI:  plugin url
Description: Basic WordPress Plugin to list recent posts
Version:     1.0
Author:      Tech In Area
Author URI:  https://www.techinarea.com
License:     GPL2
License URI: Licence URl
*/
?>

Here some information are required and some are optional, I will explain to them all below.

Plugin Name: (required) The name of your plugin
Plugin URI: The home page of the plugin website
Description: A short description of the plugin which is displayed in WordPress backend
Version: The current version number of the plugin like 1.0
Author: The name of the plugin’s author/developer
Author URI: The author’s website URL
License: Name of the plugin’s license
License URI: Link of the license URL

After saving the file you can see that your plugin is now listed in the WordPress backend plugins list. Log in to your WordPress admin backend, navigate to the Plugins menu from the left sidebar and you can see your plugin name listed there.

create a custom WordPress plugin from scratch

4. Create custom code of the plugin

After finishing the basic plugin setup we can now move to the next step of functionalities development and define what it should work.

Important hooks to keep plugin clean:

  • register_activation_hook — It will run when your plugin is activated.
<?php
register_activation_hook( __FILE__, 'my_custom_plugin_activation' );
function my_custom_plugin_activation() {
//YOUR CODE 
}
?>
  • register_deactivation_hook — It will run when your plugin is deactivated.
<?php
register_deactivation_hook( __FILE__, 'my_custom_plugin_deactivation' );
function my_custom_plugin_deactivation() {
//YOUR CODE
}
?>
  • register_uninstall_hook — It will run when your plugin is uninstalled.
<?php
register_uninstall_hook( __FILE__, 'my_custom_plugin_uninstall' );
function my_custom_plugin_uninstall() {
// Uninstallation stuff here
}
?>

We can also override default WordPress functions by using different types of hooks.

There are two types of hooks:

1. Actions hooks: To override WordPress’s core functionalities.

2. Filter hooks: For altering the WordPress content.

Eg:

function custom_setup_post_type() {
    $args = array(
        'public'    => true,
        'label'     => __( 'Custom Post', 'textdomain' )
    );
    register_post_type( 'custom_post', $args );
}

add_action( 'init', 'custom_setup_post_type' );

5. Creating custom database tables for your WordPress plugin

Creating the database tables and inserting the data functions.

<?php

global $tia_db_version;
$tia_db_version = '1.0';

function tia_install() {
	global $wpdb;
	global $tia_db_version;

	$table_name = $wpdb->prefix . 'custom_table';
	
	$charset_collate = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE $table_name (
		id mediumint(9) NOT NULL AUTO_INCREMENT,
		time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
		name tinytext NOT NULL,
		text text NOT NULL,
		url varchar(55) DEFAULT '' NOT NULL,
		PRIMARY KEY  (id)
	) $charset_collate;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );

	add_option( 'tia_db_version', $tia_db_version );
}

function tia_install_data() {
	global $wpdb;
	
	$welcome_name = 'Mr. WordPress';
	$welcome_text = 'Congratulations, you just completed the installation!';
	
	$table_name = $wpdb->prefix . 'custom_table';
	
	$wpdb->insert( 
		$table_name, 
		array( 
			'time' => current_time( 'mysql' ), 
			'name' => $welcome_name, 
			'text' => $welcome_text, 
		) 
	);
}

Calling the functions when the plugin activated.

register_activation_hook( __FILE__, 'tia_install' );
register_activation_hook( __FILE__, 'tia_install_data' );

6. Creating shortcode in a custom plugin

Creating a WordPress shortcode to list all the recent posts.

add_shortcode( 'recent-post-list', 'recent_post_listing' );
function recent_post_listing( $atts ) {
    ob_start();
    $args=array(
        'post_type' => 'post', // Post Type Slug
        'posts_per_page' =>-1, // Show All
        'order'=> 'Desc'
    );

    $new = new WP_Query($args);
    while ($new->have_posts()) : $new->the_post();
    ?>

        <div class="single_post">
            <div class="span6">
                <div class="post_title">
                     <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
                </div>
            </div>
            <div class="span6">
                <?php the_content(); ?>
            </div>
        </div>

    <?php
    endwhile;
    wp_reset_query(); 
    $return = ob_get_clean();
    return $return;
}

 

Check out my blog on How to create a custom WordPress theme and Widget

Comments are closed, but trackbacks and pingbacks are open.