How to create WordPress plugin from scratch?

How do WordPress plugins work?

A WordPress Plugin is a set of one or more functions, that specifies set of features at certain points using Plugin APIs Hooks.
Hooks allow your plugin to call functions at specific times to alter or enhance the existing functionality.

There are two kinds of hooks

  • Actions: In WordPress; an Action is a PHP function that is executed at specific points throughout the WordPress Core. For example: A developer may want to add code to the footer of a Theme. This could be accomplished by writing new function, then Hooking it to the wp_footer Action
  • Filters: In WordPress, a Filter is a function that is associated with an existing Action by specifying any existing Hook. Filters usually come with content already associated with them. They allow you to add or remove code from existing Actions.

Creating the Plugin folder with unique name

In this folder, we will create two files:

  • readme.txt
  • wp-plugin-name.php

The readme file is required if you want to host your plugin on the Plugin Directory.

File Headers

Now it’s time to put some information into your main Plugin PHP file. At a minimum, a header can contain just a Plugin Name, but several pieces should be included:

It is recommended that you prevent direct access to this file by including this line after your file headers:

Enqueueing JavaScript and CSS files

Make data available to JavaScript

Now we have some settings stored, we need to make them available to the JavaScript. “wp localize script” can be used to make any data available to your script that you can normally only get from the server-side of WordPress.

Activation and Deactivation hooks

register_activation_hook and register_deactivation_hook, run their callbacks on activation and deactivation of the plugin and perform the required functionality like adding or erasing the plugin’s metadata.

Full Example:

Why Do We Use Activation/Deactivation Hooks

We can create basic plugins without considering activation and deactivation functions. But advanced plugin will require these functions to provide additional features:

  • Create custom database tables on activation to store data and remove tables on deactivation.
  • Create custom options for plugins and activation and reset in deactivation.
  • Validate other dependent plugins on activation.
  • Any other necessary task you need to execute inactivation.

Learn more about the similar topics:
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.