Créer son plug-in pour wordpress [Partie 4]
Pour rappel, cet article fait partie de la série intitulée Créer son plugin pour WordPress
1. Widgets, définition
Un widget est, en fait, simplement un plugin qui affichera des informations dans un bloque sur votre barre latéralle. Ceci étant dit, il n’y a qu’une action à utiliser pour créer un widget.
Cette action est nommée widgets_init – vous pouvez donc l’apeller de cette façon : add_action(‘widgets_init’, function_name);
Une fois ceci effectué, vous devrez alors « enregistrer » deux fonctions, mais uniquement si le système de sidebar est bien actif. Cet enregistrement s’éffectue dans la fonction précédement déclarée.
Voici un bout de code qui fera l’affaire :
function function_name() {
if ( !function_exists('register_sidebar_widget') || !function_exists('register_widget_control') )
return;
register_sidebar_widget(string $name,callback $function);
// register_sidebar_widget prend en paramètres le nom du widget ainsi que la fonction qui gère l'affichage.
register_widget_control(string $name, callback $function2);
// register_widget_control prend en paramètres le nom du widget ainsi que la fonction qui gère les optiosn (visible depuis l'onglet apparence dans l'administration).
}
Voila, c’est a peu près tout ce que vous avez besoin de savoir pour créer un plugin. Le reste n’est pas spécifique aux widgets (options, branchements, appels à l’API, etc…)
2. Widget d’exemple
Ci-dessous vous trouverez un exemple tout simple de widget qui n’affichera qu’un Hello World ainsi que la possibilité de modifier le titre du widget (dans les options).
/*
Plugin Name: ZenDreams_Sample_Widget
Plugin URI: http://www.zen-dreams.com/
Description: Sample Widget
Version: 1.0
Author: Anthony PETITBOIS
Author URI: http://www.zen-dreams.com/
*/
class myWidget {
function myWidget() {
add_action('widgets_init', array(& $this, 'init_widget'));
}
function init_widget() {
if ( !function_exists('register_sidebar_widget') || !function_exists('register_widget_control') )
return;
register_sidebar_widget(array('myWidget','widgets'),array(& $this, 'widget'));
register_widget_control(array('myWidget', 'widgets'), array(& $this, 'widget_options'));
}
function widget($args) {
global $wpdb;
$WidgetTitle=get_option('mywidget_options');
extract($args);
echo $before_widget.$before_title.$WidgetTitle.$after_title;
echo 'Hello World !';
echo $after_widget;
}
function widget_options() {
if ($_POST['mywidget_options']) {
$option=$_POST['mywidget_options'];
update_option('mywidget_options',$option);
}
$option=get_option('mywidget_options');
echo '<label for="mywidget_options">Title : <input id="mywidget_options" name="mywidget_options" type="text" value="'.$option.'" /></label>';
}
}
$myWidgetVariable= new myWidget ();
Comments are closed.