You get a bonus - 1 coin for daily activity. Now you have 1 coin

WORDPRESS 26 Writing a plugin

Lecture



Introduction

Up to WordPress version 1.2, the ability to change its functionality “to fit your needs” or to expand its capabilities was achieved by editing the source code of the Wordpress platform core (roughly speaking, kernel hacking). But this created various inconveniences (for example, when updating versions), and this practice was soon abandoned. The developers have implemented a fairly convenient, understandable and easy-to-use programmers system for expanding the functionality with the help of "plug-ins." The main idea of ​​using the new expansion system was to keep the kernel complete and unchangeable and at the same time give PHP programmers the ability to change its behavior with the help of special easily plug-in (and disconnectable) plug-in scripts. So what is a wordpress plugin?

WordPress Plugin

A WordPress plugin is a program or set of functions written in PHP that adds a specific set of features or services to a WordPress blog that can be easily combined with the WordPress control system and functionality using the Plugin Application Program Interface (API).

If you want to add or change any Wordpress functionality, the first thing you need to do is look for ready-made solutions in a variety of plugin repositories - maybe someone has already created a plugin that will satisfy your needs. If you didn’t find anything, this article will help you understand the process of creating your own plugins.

This article assumes that you are already familiar with the basics of WordPress functionality, as well as with the PHP programming language.

To start creating plugins, you must be registered at https://developer.wordpress.org/

Resources

  • Plugin Resources is a comprehensive list of articles and tools for plugin developers, including detailed articles on writing plugins and articles on specific “narrow” topics.
  • Another good way to learn how to use plugins is to look at the source PHP codes of well-written plugins, such as Hello Dolly (a plugin included in the WordPress basic distribution).
  • If you wrote a WordPress plugin, read Plugin Submission and Promotion to learn how to distribute your plugin.

Creating a plugin

This part of the article will give you an idea of ​​what steps you should follow to create your own plugin.

Names, files and locations

Plugin name

The first task when creating a plugin is to think about what the plugin will do and come up with a name for it (preferably a unique one). Check "Plugins" and other repositories to make sure that the name you have invented is unique; You can also google by your chosen name. Most plugin developers choose names that reflect the functionality of their plugin; for example, a weather plugin may have the word “weather” in the title. A name may consist of several words.

Plugin files

The next step is to create a PHP file with a name derived from the name of the plugin. For example, if your plugin is called Fabulous Functionality, you can name your file fabfunc.php. Again, try creating a unique name. People who install your plugin will put this file in their plugin directory, wp-content / plugins /, and no pair of plug-ins used should have the same file name.

Another option is to split your plugin into several files. Your plugin must have at least one PHP file; it may also contain JavaScript files, CSS, images, language files, etc. If your plugin consists of several files, set a unique name for the directory in which they are located, and for the main PHP file, such as fabfunc and fabfunc.php in our example, put your files in this directory and allow users to set the whole directory to wp-content / plugins /.

In this article, “PHP plugin file” means the main PHP file, which is located in the wp-content / plugins / directory or in its subdirectory.

Readme file

If you want to place your plugin on http://wordpress.org/extend/plugins/, you need to create a readme.txt file in a standard format and include it in your plugin. See http://wordpress.org/extend/plugins/about/readme.txt for format explanations.

Homepage

It is also very convenient to create a web page that plays the role of the "home page" of your plugin. This page should explain how to install the plugin, what it does, which versions of WordPress are compatible with, what has changed from version to version of your plugin, and how to use it.

File headers

It's time to add some information to your main PHP file.

Standard plugin information

The beginning of your file should contain a standard information header. This title allows WordPress to understand that your plugin exists, add it to the plugin control panel, where it can be activated, load it and run its functions; without a title, your plugin will never be activated and launched. Here is the header format:

 <? php
 / *
 Plugin Name: Plugin Name
 Plugin URI: http: // page_ with_description_plugin_and_of_updated
 Description: A brief description of the plugin.
 Version: The version number of the plugin, for example: 1.0
 Author: Plugin Author Name
 Author URI: http: // author_plugin_page
 * /
 ?>

The minimal information WordPress needs to discover your plugin is its plugin name. The rest of the information (if any) is used to create a table of plugins on the page for managing plugins. The row order is unimportant.

License

The standard header is usually followed by the license information for the plugin. Most plug-ins use a GPL license or a license compatible with the GPL. To specify a GPL license, add the following lines to your plug-in file:

 <? php
 / * Copyright YEAR_AVTORA_PLOGINA_NAME (email: E-MAIL_AVTORA)

     This program is free software;  you can redistribute it and / or modify
     it published under the GNU General Public License as published by
     the Free Software Foundation;  either version 2 of the License, or
     (at your option) any later version.

     It will be useful,
     but WITHOUT ANY WARRANTY;  without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this program;  if not, write to the free software
     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 * /
 ?>

Plug-in programming

Now it's time to get your plugin to do something. This part of the article contains several basic ideas for developing plug-ins, and explains how to perfect several tasks that your plugin will do.

Hook plugin

So, how do the components of the system interact with the plugin + core Wordpress? In order for plugins to have an opportunity to influence the Wordpress core operation or the final result of its actions, a system of so-called hooks was invented (often without translation, they are called hooks from the English hook - hook, hook). The principle of its operation is that each more or less important elementary function in the Wordpress core before returning some result of its work or performing some important action (for example, display the contents of the record on the page, or query the database) “Tries” to execute additional instructions (lines of code) intended specifically for it in the plug-in files. She makes such an attempt with the help of hooks that are written in the body of this function. Here is an example of calling plugin hooks from the Wordpress core:

 <? php
 function get_the_title ($ id = 0) {
 ...
 ...
  return apply_filters ('the_title', $ title, $ post-> ID);  // Example of hooks for the function get_the_title ();
 }
 ?>

If there is code in the plugin intended to change the behavior of one of the standard kernel functions, it will be executed by the function for which it was assigned. If not, the kernel function will work as usual.

For example, before WordPress adds a header to a post, it first checks whether any plug-in has registered functions for a hook called the_title.

 <? php
 ...
  add_filter ('the_title', 'my_own_function_for_title');  // This is how registration in the plug-in file of the new function my_own_function_for_title ();  with additional instructions for the 'the_title' hook.
 ...
 ?>

If it has, the header text is “skipped” through each such registered function, and the final result is displayed.

 <? php
 ...
 / * So in a plugin, the function that modifies Wordpress headers may look like.  In this case, it causes each word in the heading to be output with a capital letter. 
 * /
  my_own_function_for_title ($ title) {
       $ title = ucwords ($ title);
       return $ title;
 } 
 ...
 ?>

Thus, if your plugin has to add some information to the post header or change it, it should have a hook-filter for the_title and it should contain a function that makes all the necessary changes with the headers.

Another example is a hook called wp_footer. Before the end of the HTML page that WordPress generates, it checks if any plugins have a registered function for wp_footer, and runs it if it finds one.

All leads in Wordpress are divided into two categories - Filters and Actions. (filters and actions respectively). Filters (filters) are really designed to "filter" (change) any data before they are displayed on the page or added to be stored in the database. This filtering of spam, errors or simply erroneous input in the forms from which, in fact, came the English name. And the second (actions, actions) are intended to replace various actions of the kernel with your actions (for example, changing the query string to the database), in programming this change in the actions of the basic functionality is also called overload.

You can learn more about how to register functions for Filters and Actions, and which kernel actions can be changed in WordPress, in the Plugin API. If you find a place in the WordPress code where you would like to have an Action or Filter, but it isn’t in WordPress, you can offer new leads (suggestions are generally accepted); You can find out how to do this in Reporting Bugs.

Template tags

Another way to add functionality with a plugin is to create template tags. Anyone who wants to use your plugin can add these tags to their theme, to the panel, to the post content section, or to another appropriate place. For example, a plugin that adds geographic tags to posts can define a template tag function called geotag_list_states () for a sidebar that lists all posts tagged with geo tags, with a link to the archive of the plugin pages.

To declare a template tag, simply write a PHP function, and document it for plug-in users on your plugin page and / or in the main plug-in file. A good idea, documenting a function, is to give an example of execution containing <? Php and?> That you need to add to the topic to get the result ..

Saving plugin data in the database

Most plug-ins get some information from the blog owner or from his users for use in filters, actions, and template functions that need to be stored between sessions. This information requires saving in WordPress for a long time between sessions. Here are two basic methods for storing data in the database:

  1. Use the WordPress settings mechanism (described below). This method is designed to store relatively small amounts of named static information — data that the blog owner enters when the plug-in is first run, and then rarely changes.
  2. Create a new separate table in the database. This method is intended for data associated with specific records, pages, applications, or comments — data that grows over time and that do not have individual names. See Creating Tables with Plugins for information on how to create a plug-in table.

WordPress Settings Engine

Information on how to create a page that automatically saves your settings can be found in the article “Creating Customization Pages”.

WordPress has a mechanism for saving, updating, and retrieving individual named data stored in the WordPress database. Setting values ​​can be strings, arrays, or PHP objects (they will be serialized or converted to a string before writing, and deserialized before extraction). The names of the settings are strings, and they must be unique, so as not to conflict with Wordpress or other plugins.

Here are the main features your plugin can use to access WordPress preferences:

 add_option ($ name, $ value, $ deprecated, $ autoload);

Creates a new setting; does nothing if the option already exists.

$ name

Required (string). The name of the setting.

$ value

Optional (string), the default is an empty string. Setting value.

$ deprecated

Optional (string), no longer used by WordPress. You can pass an empty string or null to use the $ autoload parameter following it.

$ autoload

Optional, defaults to yes (enum: yes or no). If set to yes, the settings are automatically retrieved by the get_alloptions function.

 get_option ($ option);

Retrieves the setting value from the base.

$ option

Required (string). The name of the setting whose value you want to get. A list of default settings created during WordPress installation can be found in the Option Reference.

 update_option ($ option_name, $ newvalue);

Updates or creates a setting value in the database (note: you can not call add_option if you do not need the $ autoload parameter).

$ option_name

Required (string). The name of the setting to update.

$ newvalue

Required. New setting value.

Admin panels

Provided that your plugin has some options stored in the WordPress database (see section above), you probably want to have an administrative panel that allows users to view and edit the settings of your plugin. Methods for creating panels are described in the article “Adding Administrative Menus”.

Plugin internationalization

After you have finished writing your plugin, you need to internationalize it (provided that you plan to distribute your plugin). Internationalization is the process of setting software for localization ; Localization is a process of translating text displayed by a program into various languages. WordPress is used all over the world, and internationalization and localization are built into its structure, including the localization of plug-ins. Details of using GNU gettext to localize WordPress can be found in Translating WordPress.

It is highly recommended to internationalize your plugin so that people from different countries can localize it. The process is simple:

  • Choose a name for your plugin's translation space. It is usually the same as the name of the main file of your plug-in (only without .php). The name must be unique.
  • Wherever your plugin uses strings of text that will be shown to the user (known as “messages”), enclose them in one of the two WordPress gettext functions. Notice that in your plugin you have to use the second argument — the name of the translation space you chose (in the WordPress core, the $ domain argument remains empty).

__ ($ message, $ domain)

Translates $ message using the current locale for $ domain. Wrap the lines you are going to use in calculations in this function.

_e ($ message, $ domain)

Translates $ message using the current locale for $ domain, and displays it. Wrap the lines that you want to show to the user in this function.

  • Create a POT file for your plugin (translation catalog for all translated messages) and distribute it with the plugin. Users will need to put the MO-translation file in the directory of your plugin and name it domain-ll_CC.mo, where ll_CC is the name of the desired locale. For information on POT, MO and locales, see Translating WordPress.
  • Load the translation for the current locale and your text space using the load_plugin_textdomain function before the gettext functions are called, but as late as possible in the session (because some multilingual plugins change the locale when they are loaded). One of the possible implementations is the declaration of the initialization function, which is called above all the functions of your plugin. For example, your text space is called “fabfunc”:
 $ fabfunc_domain = 'fabfunc';
 $ fabfunc_is_setup = 0;

 function fabfunc_setup ()
 {
    global $ fabfunc_domain, $ fabfunc_is_setup;

    if ($ fabfunc_is_setup) {
       return;
    } 

    load_plugin_textdomain ($ fabfunc_domain, PLUGINDIR. '/'. dirname (plugin_basename (__ FILE__)));
 }

If your plugin is not in its own subdirectory, the second argument of the load_plugin_textdomain function can be omitted.

If you are reading this section in order to internationalize the topic, you can follow the above recommendations, with some exceptions:

  • The MO file needs to be copied to the theme directory (next to style.css).
  • The MO file should be called ll_CC.mo, where ll_CC is the name of the locale (that is, the name of the space should not be part of the file name).
  • To load the name of the translation space, paste the following code (with a PHP header, if necessary) into the functions.php file of your theme:
 load_theme_textdomain ('space_name');

Plugin Design Tips

This is the last part of the article, which includes various tips on plugin development.

  • The plugin code must comply with WordPress development standards. Please also take into account the standards of inline documentation.
  • All functions of your plugin must have unique names, different from the names of WordPress core functions, other plugins or themes. For this reason, it is a good idea to use a unique prefix for the names of the functions of your plugin. Another possibility is to declare your functions inside a class (which must also have a unique name).
  • Do not explicitly use the WordPress database prefix (usually “wp_”) in your plugin. Instead, use the $ wpdb-> prefix variable.
  • Reading the database is an easy process, but writing to the database is difficult. The databases are exceptionally good at collecting data and issuing it; these operations are usually performed quickly. Making changes to the database is a more complex process, and therefore more resource-intensive.As a result, try to reduce the number of entries in the database. Keep everything ready in the code, then you can only make those entries in the database that you really need.
  • Выбирайте из базы при помощи SELECT только то, что вам нужно. Даже несмотря на то, что базы извлекают данные достаточно быстро, вы можете уменьшить нагрузку на базу, выбирая только те данные, которые вам нужны. Если вам нужно подсчитать количество строк в таблице, не используйте SELECT * FROM, потому что все данные всех строк будут занимать память. Подобно этому, если вам нужны только post_id и post_author в вашем плагине, выбирайте с помощью SELECT только эти конкретные поля, чтобы уменьшить нагрузку. Помните: сотни других процессов могут обращаться к базе одновременно с вами. База и сервер могут только распределять ресурсы между процессами. Изучите, как минимизировать обращения вашего плагина к базе, чтобы гарантировать, что ваш плагин не злоупотребляет ресурсами.

Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Content Management Systems (CMS)

Terms: Content Management Systems (CMS)