Create Plugins for WordPress
Create Plugins for WordPress
Like any self-respecting CMS, WordPress offers its users the ability to expand its functions through plugins. It has a very large repository where to find what we need, but what happens if we do not? We need to develop the functionality we seek. If you are in this situation, welcome to the first class of plugins:WordPress Plugin Development .
We’ll start with the basics. We all know what a plugin, but it is worth remembering a few things.
Why in a plugin?
The main advantage is clear: do not touch the system . Playing the system is a mortal sin! No, no, we should not except in very concrete and specific, in that we know what we’re playing. Remember that when you upgrade WordPress to a new version, the changes you’ve made directly on the system will lose . No, it’s much better to create a new plugin, which will continue to operate regardless of the version (up) of WordPress to be updated, without losing a single line of code, as long as you use functions in your plugin are supported by WordPress version in which the plugin acts. You can activate and deactivate a plugin with only one button on the administrator, which is magnificent. And of course a well done pluginSHOULD work on any WordPress where it is installed, as long as minimum version requirements are met.
Two plugins could come into conflict if the names of functions or global variables defined are equal. So it is important to differentiate well when defining functions. Now talk about it.
Required Plugins
There is a way to force WordPress to use a plugin, without going through the plugin manager or having to activate it. If we create a wp-content folder called mu-plugins , WordPress will recognize it as plugins «Must Use» (must use). But however, do not behave like normal plugins, and not recommended for use.
Plugins vs Themes
The overwhelming majority of tutorials on «how to do something (whatever) in WordPress» they say this: «It’s easy! Just include these functions in the functions.php file of the theme you have installed. » We are in the same situation as before, almost worse. The Themes are also updated , and these updateswill lose the changes you made to the file «functions.php», or tomorrow you could want to use a different theme and you would not have the functionality you have scheduled for the last.
This is not practical . It costs nothing to create a plugin and copy the functions there. And everything works exactly as if we had copied to the theme. It is not practical unless we want to provide a specific function of a particular theme , no matter is lost when changing theme, then it is.
Creating a plugin
Most plugins that we will go to the folder wp-content/plugins our WordPress system. Within this we must create a new folder, and name it with a key that references your plugin. As this is the first class of «Create Plugin for WordPress» and we want to put a simple tutorial, we will use: wp-content/plugins/mi_plugin.Within our new folder, create a file named my-first plugin.php
Open this file with a PHP code editor and write the header. The header is a series of lines that provide information about the WordPress plugin to display when the Dashboard, as the name, description, version, author, etc..
A simple and basic header might look like this:
<?php /* Plugin Name: Mi plugin Plugin URI: https://www.codigonexo.com/ Description: Crear Plugins para WordPress, clase I Author: Juan Viñas Author URI: https://www.codigonexo.com/ Version: 1.0 License: GPLv2 */ ?>
This header is mandatory in all plugins to do.
If you have correctly followed the steps so far, and your plugin should appear in the list of our WordPress plugins. Yes, switch it off does nothing, obviously, since we have not scheduled any functionality.
By providing functionality to the plugin
From here, whatever you want that your plugin does, is totally up to you. It depends on your imagination.But not enough to write functions and call them.
WordPress has a number, or rather, a HUGE number of » hooks «. We’ve talked about them sometime, but we will explain the concept.
A » Hook «or» hook «in WordPress, is a time when the system load to which we can attach our functions.That is, for example, if we need to add a new menu to the WordPress administrator, program the corresponding function, and then we associate the hook «admin_menu», so that when it is charging the administration menu, our function is executed. Very handy, right?
The hooks are called for «actions» or for «filters» with add_action or add_filter . What is the difference?
- Actions : Actions are those hooks that the system will launch at specific points during execution, or when specific events occur. Your plugin can specify that its functions be thrown at these points, using the API of shares.
- Filters : Filters are hooks that WordPress launches to modify text of various types before adding them to the database, or before they are displayed on the screen. Your plugin can specify that its functions are implemented to modify certain texts at these points, using the Filter API.
Occasionally, use an action or filter will lead to the same result, regardless of what we use. For example, if you want your plugin to change the text of a post, you can add an action to hook ‘publish_post’ (which shall modify when stored in the database), or use a filter on the hook ‘ the_content ‘(and the content will be modified when displayed on screen). You can read more about this in the Codex .
If we do not associate a function to a hook, this will never be executed unless during normal execution of the system (on a theme, or elsewhere in our plugin) call it directly.
When creating functions, we must be very careful. If two plugins implement the same function, the result is a serious error in the system that prevents this charge. Thus, it is strongly recommended:
- Differentiate our functions and global variables properly, inventing some kind of code or word to make our unique plugin, or as unique as possible. We can not know, of course, if another developer in another corner of the world will implement exactly the same function name, with the same distinctive, and it will give the chance at a third corner of the planet from one user to install the two plugins in WordPress, all right. But we can try. For example, in this case, we will call our function with the prefix «my_plugin». Well, it’s a bad example, how many plugins start with ‘my_plugin’? So many, fixed. Maybe we could give it a spin, it’s ‘-mip_’, ‘__miplugin_’, ‘codigonexo_mi_plugin’, or whatever comes to mind.Remember that then you have to use it, and the longer, more difficult to remember and be more tedious to rewrite.
- Check that it does not exist function before defining it. This step is much smarter than the last (but not a substitute, for the record). If the function already exists, not directly define ours. This does not solve the problem we mentioned before, but in this case, instead of causing an error in the system, our plugin will simply not work. You can do so:
if(!function_exists('mi_plugin_function')){ function mi_plugin_function(){ // Contenido de la función } }
And then, when making use of this function somewhere in the plugin, check if the function exists, but in reverse:
if(function_exists('mi_plugin_function')){ mi_plugin_function(); }
On the other hand, we also know that WordPress has functions for (almost) everything in the system. Want to add a menu? add_menu_page. Want to send an email? wp_mail. Want to get the title of a post? get_the_title. Have you invented a new shortcode? add_shortcode. So when we think of something to do on the system, remember these tips before you start coding:
Probably someone has come up before you . And this is not bad, on the contrary, someone has left the head to get it, and usually, the solution tends to be on the Internet more or less hidden.
If Google is the best friend of a developer, the WordPress Codex is the second best friend of a WordPress developer (the first is still Google). Not only for being the official WordPress documentation for developers, but because also their forums are rich in rare questions noses , which in many cases either we clarify the doubt, or put us on the track. A must know English, but that’s something that applies to our entire profession, should not be a serious problem …
Another great place to look is Stack Overflow , but generally, when you Google, one of the first sites that comes with answers and often more effective.
Do not be afraid to ask .
If none of these tips really has solved your problem or I got a little easier, remember that nothing is impossible. Try to simplify the problem , divide it into parts, and seeks solutions to each part. Do not get stuck, do not focus on an issue that will not see unless you have no solution alternative. If you move to another where despejarte easier task when you see it all again perhaps clearer. And above all, never be discouraged .
Now we will develop a small example consisting of a submenu in the «Settings» menu and a page where you can keep options directly in the WordPress database.
Menu
As already mentioned, WordPress has functions for all the «typical» that plugins do. Add a submenu to the Adjustments section falls within normal, so it includes WordPress, and we can do like this:
function miplugin_menu_opciones(){ add_options_page('Título de la pagina','Título del menu','read','miplugin-ops','miplugin_pagina_de_opciones'); }
Although here we use the » add_options_page «actually this generic function call to create submenus,»add_submenu_page «just do not have to worry about specifying where to hang this submenu. The five parameters are: the page title (which appears above the browser and on the tab), the title that appears in the submenu, the minimum permission the user must have to view this submenu (‘read’ is the lower, open to all users with access to wp-admin), an unique slug for this menu, and the call to the function to be executed when you press this menu.
Eye ! If your plugin you want to create a custom type, it is necessary to create a specific menu for himas it will automatically create the menu, the submenu list of tickets and the submenu to create new entry. If you want to add more things (options, other pages), it must create submenus (except for taxonomies, these also create their own menus where applicable).
Do not work? Obviously, what we have said about the hooks? Add ye this line just below the function.
add_action('admin_menu','miplugin_menu_opciones');
add_action adds, when it happens ‘admin_menu’, execution of function ‘miplugin_menu_opciones’, ie putting the sub in place.
The features page
When we add a menu parameter specified as ‘miplugin_pagina_de_opciones’. This is the function to execute when accessing our submenu. So let’s define it, in fact, what this function will do is display an HTML form …
function miplugin_pagina_de_opciones(){ ?> <div class='wrap'><h2>Opciones de mi sitio</h2></div> <form method='post'> <input type='hidden' name='action' value='salvaropciones'> <table> <tr> <td> <label for='telefono'>Telefono</label> </td> <td> <input type='text' name='telefono' id='telefono' > </td> </tr> <tr> <td> <label for='direccion'>Dirección</label> </td> <td> <input type='text' name='direccion' id='direccion' > </td> </tr> <tr> <td> <label for='email'>Email</label> </td> <td> <input type='text' name='email' id='email' > </td> </tr> <tr> <td colspan='2'> <input type='submit' value='Enviar'> </td> </tr> </table> </form> <?php }
HTML Form, incidentally, lacks functionality. If you click on Submit, nothing happens. Retoquemoslo slightly.
function miplugin_pagina_de_opciones(){ echo("<div class='wrap'><h2>Opciones de mi sitio</h2></div>"); if(isset($_POST['action']) && $_POST['action'] == "salvaropciones"){ update_option('miplugin_telefono',$_POST['telefono']); update_option('miplugin_direccion',$_POST['direccion']); update_option('miplugin_email',$_POST['email']); echo("<div class='updated message' style='padding: 10px'>Opciones guardadas.</div>"); } ?> <form method='post'> <input type='hidden' name='action' value='salvaropciones'> <table> <tr> <td> <label for='telefono'>Telefono</label> </td> <td> <input type='text' name='telefono' id='telefono' value='<?=get_option('miplugin_telefono')?>'> </td> </tr> <tr> <td> <label for='direccion'>Dirección</label> </td> <td> <input type='text' name='direccion' id='direccion' value='<?=get_option('miplugin_direccion')?>'> </td> </tr> <tr> <td> <label for='email'>Email</label> </td> <td> <input type='text' name='email' id='email' value='<?=get_option('miplugin_email')?>'> </td> </tr> <tr> <td colspan='2'> <input type='submit' value='Enviar'> </td> </tr> </table> </form> <?php }
Now yes. This is a simple way to do this without much head warm us. Detected by $ _POST if they enter new data. If so, update the options update_option . In addition, the fields are filled with get_option if the option exists and has a non-null value. And in any part of our website you can retrieve these values with the same function, get_option , we set global options for the system.
( Note: the validators and error checks are up to you. The function update_option returns true or false depending on whether the data has been saved or not ).
What do you think your first plugin? Thus to the silly, now you have a plugin very useful for storing information like phone number, address, email, etc.. querráis then recover, for example, in your theme, and not have to change the theme if you’re moving, if you change your email or phone … Just change the information of the plugin.
Soon, in this series of classes on Creating Plugins for WordPress, learn the basics about the translation in a plugin, some tricks more about hooks, useful examples and case studies, and how to upload your plugin to the official WordPress repository.
«Today, most software exists, not to solve a
problem, but to interface with other software. «
– IO Angell