Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

User:Jipsou/fr:Creer Des Pages D Options

(

Page d'accueil du Codex en français - Télécharger WordPress en français
Les utilisateurs francophones se retrouvent sur le site WordPress-Francophone, notamment sur son forum d'entraide.

) (
This page is marked as incomplete. You can help Codex by expanding it.
)

This article is in transition to meet Settings API, which was introduced in Version 2.7. For information prior to 2.7 see this revision.

Présentation

Créer des panneaux d'options personnalisés dans Wordpress se révèle être relativement simple.

Tout d'abord, il vous faut créer le nouveau menu et la nouvelle page. Voir : Adding Administration Menus.

So long as you stick to this structure, WordPress will handle all of the option creation, update, saving, and redirection for you. It will check permissions, and do all that other magic behind the scenes.

Plusieurs nouvelles fonctions ont été ajoutées dans WordPress 2.7. Ces nouvelles fonctions sont facultatives dans WordPress 2.7 mais seront nécessaires à l'avenir. Elles sont indispensables pour WordPress MU 2.7. Voir Migrating Plugins and Themes to 2.7 et Settings API pour plus d'informations.

Cet article ne concerne que le codage de la page des réglages seulement. Pour plus d'information sur la façon d'ajouter une page de réglages, voir Administration Menus

À quel endroit enregistrer le code ?

Vous pouvez soit mettre le code pour votre page d'options dans le fichier php de votre plugin (ou, pour un thème, dans le fichier functions.php), soit créer un second fichier appelé options.php, par exemple, et l'appeler par la fonction "include" - http://php.net/manual/en/function.include.php

Ouvrir la page

Si vous souhaitez que votre page d'options ait l'apparence de celles existantes du panneau d'administration existant de Wordpress, utilisez ceci :

<div class="wrap">
<?php screen_icon(); ?>
<h2>Your Plugin Page Title</h2>

Balise Formulaire

Une fois que vous avez votre page, il vous faut créer un formulaire en HTML, grâce à ce code :

<form method="post" action="options.php"> 


Fonction settings_fields

Le setting fields saura quels réglages gérera votre page d'options.

Après la balise d'ouverture du formulaire, ajoutez cette fonction :

settings_fields( 'myoption-group' );

myoption-group est le même nom utilisé dans la fonction register_setting.

Cette fonction remplace les nonce magic, action field, et page_options field que requiert les versions antérieures à la Version 2.7.

do_settings_fields Function

After the settings_fields() call, add this function

do_settings_fields( 'myoption-group' );

This function replaces the form-field markup in the form itself.

Balises de fermeture

Bien évidemment, il faut fermer la balise du formulaire après vos options et, si vous le souhaitez, vous pouvez ajouter un bouton "Mise à jour des options". Celui par défaut est celui-ci :

<?php submit_button(); ?>
</form>
</div>

Vous pouvez personnaliser ce bouton par la fonction submit_button.

Note the use of the _e() function to handle translation of the text, see Localizing WordPress for more info. Info : l'utilisation de la fonction _e() permet la traduction du texte. Voir Localizing WordPress pour plus d'info. (je n'en vois pas ??)

Register Settings

Les fonctions register_setting et unregister_setting permettent d'ajouter et suppprimer des options disponibles sur une liste des options autorisées que le formulaire est capable d'enregistrer.Elles peuvent également appeler une fonction de rappell

The register_setting and unregister_setting functions add and remove options from a whitelist of allowed options that the form is able to save. They can also name a sanitize callback function as a security measure to check each option's value.

The register_setting function should be called in an admin_init action, which runs before every admin page and in particular, options.php, which receives this form.

Your plugin probably has a section with an add_action that adds a new menu item to the administration menus. This line will be in the same section to add an action to admin_init.

if ( is_admin() ){ // admin actions
  add_action( 'admin_menu', 'add_mymenu' );
  add_action( 'admin_init', 'register_mysettings' );
} else {
  // non-admin enqueues, actions, and filters
}

Then you create a new function that registers each option.

function register_mysettings() { // whitelist options
  register_setting( 'myoption-group', 'new_option_name' );
  register_setting( 'myoption-group', 'some_other_option' );
  register_setting( 'myoption-group', 'option_etc' );
}

The name of myoption-group doesn't matter but it has to match the name used in the settings_fields function above.


See It All Together

Please note: Some of the code in this example (particularly do_settings) is deprecated. View Otto's tutorial here for better examples of workable code. In addition, there's another article available by ozh.

To add icon to for your options page use the following code [this will work on version 3.4.2 and later] In following example, icon is stored in "images" folder in theme directory.

<?php add_menu_page('BAW Plugin Settings', 'BAW Settings', 'administrator', __FILE__, 'baw_settings_page', get_stylesheet_directory_uri('stylesheet_directory')."/images/media-button-other.gif"); ?>

The below example uses the new Settings API to create and save your plugin options

<?php
// create custom plugin settings menu
add_action('admin_menu', 'baw_create_menu');

function baw_create_menu() {

	//create new top-level menu
	add_menu_page('BAW Plugin Settings', 'BAW Settings', 'administrator', __FILE__, 'baw_settings_page',plugins_url('/images/icon.png', __FILE__));

	//call register settings function
	add_action( 'admin_init', 'register_mysettings' );
}


function register_mysettings() {
	//register our settings
	register_setting( 'baw-settings-group', 'new_option_name' );
	register_setting( 'baw-settings-group', 'some_other_option' );
	register_setting( 'baw-settings-group', 'option_etc' );
}

function baw_settings_page() {
?>
<div class="wrap">
<h2>Your Plugin Name</h2>

<form method="post" action="options.php">
    <?php settings_fields( 'baw-settings-group' ); ?>
    <?php do_settings( 'baw-settings-group' ); ?>
    <table class="form-table">
        <tr valign="top">
        <th scope="row">New Option Name</th>
        <td><input type="text" name="new_option_name" value="<?php echo get_option('new_option_name'); ?>" /></td>
        </tr>
         
        <tr valign="top">
        <th scope="row">Some Other Option</th>
        <td><input type="text" name="some_other_option" value="<?php echo get_option('some_other_option'); ?>" /></td>
        </tr>
        
        <tr valign="top">
        <th scope="row">Options, Etc.</th>
        <td><input type="text" name="option_etc" value="<?php echo get_option('option_etc'); ?>" /></td>
        </tr>
    </table>
    
    <?php submit_button(); ?>

</form>
</div>
<?php } ?>

Example #2

This example works on WP 3.5.1. Much simpler and simply works. This is an updated version of Otto's tutorial.

<?php
class wctest{
    public function __construct(){
        if(is_admin()){
	    add_action('admin_menu', array($this, 'add_plugin_page'));
	    add_action('admin_init', array($this, 'page_init'));
	}
    }
	
    public function add_plugin_page(){
        // This page will be under "Settings"
	add_options_page('Settings Admin', 'Settings', 'manage_options', 'test-setting-admin', array($this, 'create_admin_page'));
    }

    public function create_admin_page(){
        ?>
	<div class="wrap">
	    <?php screen_icon(); ?>
	    <h2>Settings</h2>			
	    <form method="post" action="options.php">
	        <?php
                    // This prints out all hidden setting fields
		    settings_fields('test_option_group');	
		    do_settings_sections('test-setting-admin');
		?>
	        <?php submit_button(); ?>
	    </form>
	</div>
	<?php
    }
	
    public function page_init(){		
	register_setting('test_option_group', 'array_key', array($this, 'check_ID'));
		
        add_settings_section(
	    'setting_section_id',
	    'Setting',
	    array($this, 'print_section_info'),
	    'test-setting-admin'
	);	
		
	add_settings_field(
	    'some_id', 
	    'Some ID(Title)', 
	    array($this, 'create_an_id_field'), 
	    'test-setting-admin',
	    'setting_section_id'			
	);		
    }
	
    public function check_ID($input){
        if(is_numeric($input['some_id'])){
	    $mid = $input['some_id'];			
	    if(get_option('test_some_id') === FALSE){
		add_option('test_some_id', $mid);
	    }else{
		update_option('test_some_id', $mid);
	    }
	}else{
	    $mid = '';
	}
	return $mid;
    }
	
    public function print_section_info(){
	print 'Enter your setting below:';
    }
	
    public function create_an_id_field(){
        ?><input type="text" id="input_whatever_unique_id_I_want" name="array_key[some_id]" value="<?=get_option('test_some_id');?>" /><?php
    }
}

$wc_enet = new wctest();

This will create something like this:

creating-options-pages-ex-2.png

Pitfalls

The Settings name, the second parameter in the register_setting() function, MUST match the name of the option being updated in the database!
For example, say you have add_option( 'foo_bar', 'isfoo' ), you MUST use foo_bar as the second parameter for the register_setting() function. Otherwise WordPress does not know which setting it is suppose to update and it will fail to update.