WordPress.org

Codex

User:zenbien/fr:Developper un plugin

Contents

Introduction

L'objectif principal de l'utilisation des plugins est de maintenir le noyau de Wordpress intact, dans un soucis de stabilité et de mise à jour des futures versions.

Définition

Un plugin WordPress est un programme, écrit en langage PHP, permettant d'ajouter des fonctionnalités personnalisés à Wordpress.

Ressources

  • Il existe une multitude d'articles et de ressources pour les développeurs de plugins dans la section Plugin Resources
  • Une bonne méthode pour comprendre le fonctionnement des plugins, est de regarder le code source du plugin suivant : Hello Dolly, installé par défaut sur wordpress
  • Faites la promotion de votre plugin sur le site Plugin Submission and Promotion

Créer un plugin

Le nom du plugin

Veillez à ce que le nom de votre plugin soit unique (voir la liste des plugins déposés Plugins ) La plupart des développeurs choisissent un nom en rapport avec la description du plugin, ce nom peut avoir plusieurs mots.

Les fichiers

Encore une fois, choisissez un nom unique (pour éviter les conflits de doublons) en utilisant la convention de nommage des variables: - 1ère lettre en minuscule. - Majuscule avec la première lettre de chaque mot. - ex: superPlugin.php

Votre plugin peut contenir plusieurs fichiers, dans ce cas il faut mettre ces fichiers dans un répertoire du même nom que votre fichier principal. ex: wp-content/plugins/superPlugin/superPlugin.php...

Fichier lisez moi

Si vous voulez diffuser votre plugin sur le site de wordpress http://wordpress.org/extend/plugins/, vous devez créer un fichier readme.txt dans un format standardisé, et l'inclure dans votre plugin. Voir http://wordpress.org/extend/plugins/about/readme.txt pour une description du format à respecter.

Informations en-tête

Votre fichier php principal doit contenir en en-tête, les informations concernant votre plugin. Celui-ci permettra à wordpress de localiser son existence, il pourra ainsi être activé dans l'administration des plugins. Sans cet en-tête, votre plugin ne pourra pas fonctionner

Exemple:

<?php
/*
Plugin Name: Nom du Plugin
Plugin URI: http://adresseContenantLesInfosSurVotrePlugin
Description: Courte description du plugin.
Version: La version du plugin.
Author: Nom de l'auteur
Author URI: http://siteWebAuteur
*/
?>

License

Faites suivre l'en-tête du fichier par les informations de licence. Dans la plupart des cas les plugins sont développés sous GPL GPL ou bien compatible with the GPL.

Pour cela utilisez la convention suivante:

<?php
/*  Copyright ANNEE  NOM_AUTEUR_DU_PLUGIN  (email : EMAIL_AUTEUR)

    This program is free software; you can redistribute it and/or modify
    it under the terms of 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.

    This program is distributed in the hope that 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
*/
?>

WordPress Plugin Hooks

Many plugins accomplish their goals by connecting to one or more WordPress plugin "hooks". The way plugin hooks work is that at various times while WordPress is running, WordPress checks to see if any plugins have registered functions to run at that time, and if so, the functions are run. These functions modify the default behavior of WordPress.

For instance, before WordPress adds the title of a post to browser output, it first checks to see if any plugin has registered a function for the "filter" hook called "the_title". If so, the title text is passed in turn through each registered function, and the final result is what is printed. So, if your plugin needs to add some information to the printed title, it can register a "the_title" filter function.

Another example is the "action" hook called "wp_footer". Just before the end of the HTML page WordPress is generating, it checks to see whether any plugins have registered functions for the "wp_footer" action hook, and runs them in turn.

You can learn more about how to register functions for both filter and action hooks, and what plugin hooks are available in WordPress, in Plugin API. If you find a spot in the WordPress code where you'd like to have an action or filter, but WordPress doesn't have one, you can also suggest new hooks (suggestions will generally be taken); see Reporting Bugs to find out how.

Template Tags

Another way for a plugin to add functionality to WordPress is by creating custom Template Tags. Someone who wants to use your plugin can add these "tags" to their theme, in the sidebar, post content section, or wherever it is appropriate. For instance, a plugin that adds geographical tags to posts might define a template tag function called geotag_list_states() for the sidebar, which lists all the states posts are tagged with, with links to the state-based archive pages the plugin enables.

To define a custom template tag, simply write a PHP function and document it for plugin users on your plugin's home page and/or in the plugin's main PHP file. It's a good idea when documenting the function to give an example of exactly what needs to be added to the theme file to use the function, including the <?php and ?>.

Saving Plugin Data to the Database

Most plugins will need to get some input from the site owner or blog users and save it between sessions, for use in its filter functions, action functions, and template functions. This information has to be saved in the WordPress database, in order to be persistent between sessions. There are two basic methods for saving plugin data in the database:

  1. Use the WordPress "option" mechanism (described below). This method is appropriate for storing relatively small amounts of relatively static, named pieces of data -- the type of data you'd expect the site owner to enter when first setting up the plugin, and rarely change thereafter.
  2. Create a new, custom database table. This method is appropriate for data associated with individual posts, pages, attachments, or comments -- the type of data that will grow as time goes on, and that doesn't have individual names. See Creating Tables with Plugins for information on how to do this.

WordPress Options Mechanism

See Creating Options Pages for info on how to create a page that will automatically save your options for you.

WordPress has a mechanism for saving, updating, and retrieving individual, named pieces of data ("options") in the WordPress database. Option values can be strings, arrays, or PHP objects (they will be "serialized", or converted to a string, before storage, and unserialized when retrieved). Option names are strings, and they must be unique, so that they do not conflict with either WordPress or other plugins.

Here are the main functions your plugin can use to access WordPress options.

add_option($name, $value, $description, $autoload);
Creates a new option; does nothing if option already exists.
$name
Required (string). Name of the option to be added.
$value
Optional (string), defaults to empty string. The option value to be stored.
$description
Optional (string), defaults to empty string. Description of the option, which is placed into the WordPress database in case someone browses the database to see what options are there.
$autoload
Optional, defaults to 'yes' (enum: 'yes' or 'no'). If set to 'yes' the setting is automatically retrieved by the get_alloptions function.
get_option($option);
Retrieves an option value from the database.
$option
Required (string). Name of the option whose value you want returned. You can find a list of the default options that are installed with WordPress at the Option Reference.
update_option($option_name, $newvalue);
Updates or creates an option value in the database (note that add_option does not have to be called if you do not want to use the $description or $autoload parameters).
$option_name
Required (string). Name of the option to update.
$newvalue
Required. The new value for the option.

Administration Panels

Assuming that your plugin has some options stored in the WordPress database (see section above), you will probably want it to have an administration panel that will enable your plugin users to view and edit option values. The methods for doing this are described in Adding Administration Menus.

Internationalizing Your Plugin

Once you have the programming for your plugin done, another consideration (assuming you are planning on distributing your plugin) is internationalization. Internationalization is the process of setting up software so that it can be localized; localization is the process of translating text displayed by the software into different languages. WordPress is used all around the world, so it has internationalization and localization built into its structure, including localization of plugins. For background on WordPress's use of GNU gettext for localization, see Translating WordPress.

It is highly recommended that you internationalize your plugin, so that users from different countries can localize it. The process is fairly straightforward:

  • Choose a translation "text domain" name for your plugin. This is generally the same as your plugin file name (without the .php), and must be unique among plugins the user has installed.
  • Wherever your plugin uses literal text strings that will be displayed to the user (known as "messages"), wrap them in one of the two WordPress gettext functions. Note that in a plugin, you need to use the second argument, passing in the translation text domain name you chose, unlike in the core of WordPress (which leaves the $domain argument blank).
__($message, $domain) 
Translates $message using the current locale for $domain. Wrap text strings that you are going to use in calculations with this function.
_e($message, $domain) 
Translates $message using the current locale for $domain, and then prints it on the screen. Wrap text strings that you are directly printed with this function.
  • Create a POT file (translation catalog listing all the translatable messages) for your plugin, and distribute it with your plugin. Users will need to put their translated MO file in the same directory as your plugin's PHP file, and name it domain-ll_CC.mo, where ll_CC is the name of their locale. See Translating WordPress for information on POT files, MO files, and locales.
  • Load the translations for the current locale and your text domain by calling load_plugin_textdomain before either of the gettext functions is called, but as late as possible in the session (because some multi-lingual plugins change the locale when they load). One possible implementation is to define an initialization function that is called at the top of all of your plugin functions. For instance, assuming your text domain is "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, 'wp-content/plugins');
}

If your plugin is in its own subdirectory, append that to the second argument of load_plugin_textdomain.

If you are reading this section because you want to internationalize a Theme, you can basically follow the steps above, except:

  • The MO file goes into the theme directory (same place as style.css).
  • The MO file is named ll_CC.mo, where ll_CC is the name of the locale (i.e. the domain is NOT part of the file name).
  • To load the text domain, put the following (inside a PHP escape if necessary) in your theme's functions.php file:
load_theme_textdomain('your_domain');

Plugin Development Suggestions

This last section contains some random suggestions regarding plugin development.

  • The code of a plugin should follow the WordPress Coding Standards. Please consider the Inline Documentation Standards as well.
  • All the functions in your plugin need to have unique names that are different from functions in the WordPress core, other plugins, and themes. For that reason, it is a good idea to use a unique function name prefix on all of your plugin's functions. Another possibility is to define your plugin functions inside a class (which also needs to have a unique name).
  • Do not hardcode the WordPress database table prefix (usually "wp_") into your plugins. Be sure to use the $wpdb->prefix variable instead.
  • Database reading is cheap, but writing is expensive. Databases are exceptionally good at fetching data and giving it to you, and these operations are (usually) lightning quick. Making changes to the database, though, is a more complex process, and computationally more expensive. As a result, try to minimize the amount of writing you do to the database. Get everything prepared in your code first, so that you can make only those write operations that you need.
  • SELECT only what you need. Even though databases fetch data blindingly fast, you should still try to reduce the load on the database by only selecting that data which you need to use. If you need to count the number of rows in a table don't SELECT * FROM, because all the data in all the rows will be pulled, wasting memory. Likewise, if you only need the post_id and the post_author in your plugin, then just SELECT those specific fields, to minimize database load. Remember: hundreds of other processes may be hitting the database at the same time. The database and server each have only so many resources to spread around amongst all those processes. Learning how to minimize your plugin's hit against the database will ensure that your plugin isn't the one that is blamed for abuse of resources.


External Resources