How to write basic wordpress plugin

August 24, 2017

In the "wp-contents/plugins/" folder create a subfolder with the name of your plugin.
Lets say that we want to create a plugin named "my_plugin", then we create the subfolder like this.


mkdir my_plugin

Then go into the new "wp-contents/plugins/my_plugin/" folder, and create a first file, also with the name of your plugin: "my_plugin.php".


touch my_plugin.php
my_plugin.php

Open the file with your favorite editor, and put the following content on it.



The above content, defines the name and description of your plugin.


Wordpress Plugins List

What we have done so far, it is enough to display your plugin, on the Wordpress admin area.


The plugin can be Activated now, although it wouldn't do or display anything. We need to additional code for that.



Plugin Admin Menu

Lets continue by adding an admin section for our plugin

On our file my_plugin.php we add the following code:




The above code add a menu option and two submenus on the Admin area as shown on the screenshot below.


Now lets add some functionality to display some text





We can now put some additional functionality to our plugin.

For instance, we can make it display some info from the database.
We will display the name of our site, which can be obtained from the "wp_options" table.





Now lets add a form that will allow us to change the title.





Then add the needed php code to update the title, once the form is submitted.






Plugin Shortcode

Once that we have our plugin enabled, and we have prepared the needed code on the Admin side of Wordpress, we can make our plugin to display information on the public side.

In order to do that we use "shortcodes."

To create a shortcode we need to define a function to perform the actions we desired for our plugin, and we need to "add" that function using the Wordpress "add_shortcode" instruction.

As shown in the next snippet, we have created a function that will grab the name of our blog, and display it.




A Page for our Plugin

After we have defined our shortcode, we need to insert it onto a Wordpress page.

Lets create a new page, and put our shortcode on it.


Now we can open the page, and see our plugin in action!


Download source code here.