Tag Archives: action

Case of main filters/actions during initialisation of WP [reserved for developers]

[note: example with jetpack was based on version 2.3. now recent jetpack 2.4 have changed initialization according better rules explained here]

What you need to know before adding filters in plugin or theme’s file functions.php ?

The case of main filters/actions during initialisation of WP.

The time line is very visible if your read the wp-settings.php file line by line.

Launching (do_action) of plugins_loaded (#211) preceeds that of init (#306). And both occur after plugin files including loop. (#196)

196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Load active plugins.
foreach ( wp_get_active_and_valid_plugins() as $plugin )
	include_once( $plugin );
unset( $plugin );
 
// Load pluggable functions.
require( ABSPATH . WPINC . '/pluggable.php' );
require( ABSPATH . WPINC . '/pluggable-deprecated.php' );
 
// Set internal encoding.
wp_set_internal_encoding();
 
// Run wp_cache_postload() if object cache is enabled and the function exists.
if ( WP_CACHE && function_exists( 'wp_cache_postload' ) )
	wp_cache_postload();
 
do_action( 'plugins_loaded' );

Why it is important to understand filter priority during enqueuing ?

The things – including files, instancing classes, adding filter (action) – need to be done one after the other. They must give (allow) place to be modified by another plugin. Doing one of these things inside the step where plugin files are being included is not efficient and the order is only related to name of plugins and it difficult or impossible for another plugin to modify installed filters by the previous plugin. Because adding a specific filter for a specific plugin is uneasy to maintain, it is far better to follow time line and standard filter (action).

What can we learn from the launch of jetpack plugin – latest lines of jetpack.php ?

580
581
582
583
584
585
// line 4580 and...
add_action( 'init', array( 'Jetpack', 'init' ) );
add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
add_filter( 'jetpack_static_url', array( 'Jetpack', 'staticize_subdomain' ) );
 
Jetpack_Sync::sync_options( __FILE__, 'widget_twitter' );

We find two main filters (action), init and plugins_loaded… And what happen in wp-settings.php

Launching (do_action) of plugins_loaded (#209) preceeds that of init (#306).

At end of jetpack.php a function calling Twitter is fired when including plugin file (#194) ( Jetpack_Sync::sync_options( FILE, ‘widget_twitter’ ); ). This function instanciates at this time the jetpack class. So the (previous) init filter seems to be redundant and explains some difficultes with load_plugin_textdomain step. So jetpack plugin architecture need cleaning works !

About functions and objects added in functions.php of current theme.

286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
$GLOBALS['wp_locale'] = new WP_Locale();
 
// Load the functions for the active theme, for both parent and child theme if applicable.
if ( ! defined( 'WP_INSTALLING' ) || 'wp-activate.php' === $pagenow ) {
	if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) )
		include( STYLESHEETPATH . '/functions.php' );
	if ( file_exists( TEMPLATEPATH . '/functions.php' ) )
		include( TEMPLATEPATH . '/functions.php' );
}
 
do_action( 'after_setup_theme' );
 
// Set up current user.
$wp->init();
 
/**
 * Most of WP is loaded at this stage, and the user is authenticated. WP continues
 * to load on the init hook that follows (e.g. widgets), and many plugins instantiate
 * themselves on it for all sorts of reasons (e.g. they need a user, a taxonomy, etc.).
 *
 * If you wish to plug an action once WP is loaded, use the wp_loaded hook below.
 */
do_action( 'init' );
 
// Check site status
if ( is_multisite() ) {
	if ( true !== ( $file = ms_site_check() ) ) {
		require( $file );
		die();
	}
	unset($file);
}

This file is included after plugins file and roles defined. The file of the child theme is inserted after that of the parent theme. (# 287), and then launching ( (do_action) after_setup_theme (#294) preceeding init (#306). It is therefore possible to modify plugin behaviour or filters inserted by plugins. All here will only activate if this theme is the current. When reading wp-settings.php, we see that only filters (present in wp-settings) like ‘init’ can be used or modified (associated function changed or his priority…). Note that in case of child theme, the priority of after_setup_theme must set to 11. So the functions fired by the ‘child’ filter will be executed ‘after’ those of parent.

Les filtres/actions clés au démarrage de WP [réservé développeurs]

[NOTE : les exemples sont ici basés sur jetpack v2.3. La version jetpack 2.4+ a revu l’ensemble de l’initialisation selon des règles décrites ici.]

Ce qu’il faut savoir à propos de l’addition de filtres par une extension (plugin) ou via le fichier functions.php du thème actif.
Le cas particulier des filtres présents dans wp-settings.php

La ligne des temps

La suite logique de la mise en place des composants jusqu’à la délivrance de la page visiteur ou auteur (administrateur) telle que visible dans le wp-settings.

• mise en place des dropins et des mu-plugins (#157) (mu = must use).

• mise en place des fichiers des extensions ( #196 ) qui semble se faire dans le sens alphabétique. Deux situations : soit seuls les éléments sont installés et le filtre (action) est mis en queue (ce filtre pourra alors permettre le moment venu l’instantiation de la classe du plugin) – soit déjà des initialisations, instanciations sont lancées (elles ne sont dès lors plus filtrables au préalable par d’autres plugins).

196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Load active plugins.
foreach ( wp_get_active_and_valid_plugins() as $plugin )
	include_once( $plugin );
unset( $plugin );
 
// Load pluggable functions.
require( ABSPATH . WPINC . '/pluggable.php' );
require( ABSPATH . WPINC . '/pluggable-deprecated.php' );
 
// Set internal encoding.
wp_set_internal_encoding();
 
// Run wp_cache_postload() if object cache is enabled and the function exists.
if ( WP_CACHE && function_exists( 'wp_cache_postload' ) )
	wp_cache_postload();
 
do_action( 'plugins_loaded' );

Pourquoi il est important de définir la priorité du filtre dans la queue afin de maîtriser les effets désirés ?

Par défaut, la priorité d’un filtre est ajoutée au niveau 10. C’est donc sa position sur la ligne des temps de l’adjonction qui va déterminer sa place. Cela n’est donc pas parfait, on ne peut pas toujours se fier à l’ordre alphabétique du nom de l’extension. D’où la nécessité de définir précisément, en déclarant des priorités successives, par exemple que XILI-LANGUAGE sera lancée avant XTT et XD car ces deux dernières ne fonctionnent que dans l’environnement multilingue préalablement créé par XILI-LANGUAGE.

Exemple de JetPack et de bbPress pour le maîtrise du language côté admin:

Comme on le lit dans wp-settings.php, la réalisation (do_action) plugins_loaded (#209) se fait avant que les informations sur l’utilisateur connecté soient connues. Celle des filtres init (#306) est par contre activée alors que WP connait les rôles du visiteur ou de l’administrateur.

580
581
582
583
584
585
// line 4580 et suivantes
add_action( 'init', array( 'Jetpack', 'init' ) );
add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
add_filter( 'jetpack_static_url', array( 'Jetpack', 'staticize_subdomain' ) );
 
Jetpack_Sync::sync_options( __FILE__, 'widget_twitter' );

La réalisation (do_action) plugins_loaded (#209) précède celle de init (#306). Mais en sus, ce qui pose problème, dans le cas de jetpack la fonction qui appelle Twitter ( Jetpack_Sync::sync_options( FILE, ‘widget_twitter’ ); ) instancie la classe lors de l’include de jetpack… c’est donc redondant – le filtre init n’a donc pas de raison d’être puisque la fonction twitter a instancé la classe dès l’include du fichier jetpack.php … Une mise à plat s’impose.

Chaque chose en son temps et au bon moment… une bonne architecture n’est pas automatique. Il faut donc bien séparer ce qui tient de l’infrastructure (inclusion des fichiers de l’extension), de sa modification par les extensions activées (filtre plugins_loaded) et de sa personnalisation selon la personne connectée et des rôles qui lui sont attribués (filtre init) ; pour ces deux filtres cités, bien assigner les priorités.

A propos des fonctions et objets ajoutées dans functions.php du thème.

286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
$GLOBALS['wp_locale'] = new WP_Locale();
 
// Load the functions for the active theme, for both parent and child theme if applicable.
if ( ! defined( 'WP_INSTALLING' ) || 'wp-activate.php' === $pagenow ) {
	if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) )
		include( STYLESHEETPATH . '/functions.php' );
	if ( file_exists( TEMPLATEPATH . '/functions.php' ) )
		include( TEMPLATEPATH . '/functions.php' );
}
 
do_action( 'after_setup_theme' );
 
// Set up current user.
$wp->init();
 
/**
 * Most of WP is loaded at this stage, and the user is authenticated. WP continues
 * to load on the init hook that follows (e.g. widgets), and many plugins instantiate
 * themselves on it for all sorts of reasons (e.g. they need a user, a taxonomy, etc.).
 *
 * If you wish to plug an action once WP is loaded, use the wp_loaded hook below.
 */
do_action( 'init' );
 
// Check site status
if ( is_multisite() ) {
	if ( true !== ( $file = ms_site_check() ) ) {
		require( $file );
		die();
	}
	unset($file);
}

Ce fichier est inclus après la génération des rôles et la mise en place des locales. Le fichier du thème enfant est inséré avant celui du thème parent. (# 287) – Ensuite intervient la réalisation (do_action) after_setup_theme (#294) qui précède celle de init (#306). Cas particulier si thème enfant : comme le fonctions.php du thème enfant est activé avant celui du thème parent. L’adjontion du filtre/action after_setup_theme doit se faire en position 11. Les fonctions de ce filtre recouvront alors celle du thème parent.

On peut donc dans le thème adapter certaines actions ou filtres générés au préalable par les extensions. Cela ne sera donc actif que si le thème est affecté au site (thème courant). Pour ce qui concerne les filtres du wp-settings, on voit que seul les filtres ‘init’ peuvent être modifiés (changement de la fonction associée ou de sa priorité via remove_filter suivi d’un add_filter avec de nouveaux paramètres,…)

(à suivre… patience…)