[wp-hackers] What are the point in hooking the `init` when writing a plugin?

Dion Hulse (dd32) wordpress at dd32.id.au
Sat May 5 06:33:13 UTC 2012


In the case of akismet there, there's no much difference, but there
are subtle differences that don't show.

1. WordPress isn't fully loaded when plugins are included, many
functions are undefined, and not configured properly (ie. WP_Query,
and user functions)

2. Loading on init allows for other plugins to affect it, so in
Akismets case, another plugin hooked on an earlier priority than
akismet can set the $wpcom_api_key global to something useful

3. Another plugin might unhook your init function in the event that it
doesn't need to be run all the time, you should never see this in a
general plugin, but some sites have been known to unhook a plugins
relativly expensive init process and substitute it with their own for
their niche site/etc.

So it's primarily good practice due to point 1, but there are other
hidden reasons why.

another method often used is the following, although it executes
straight away and instantates itself, it leaves the grunt of the work
until WordPress is loaded before it does anything:

class Plugin_XYZ {
  function __construct() {
     add_action( 'init', array( $this, 'init' ) );
  }
}
$GLOBALS['plugin_xyz'] = new Plugin_XYZ();

On 5 May 2012 16:23, Ryan Chan <ryanchan404 at gmail.com> wrote:
> I think this is the same when you can put the code inside the main plugin file?
>
> e.g. akismet: http://plugins.svn.wordpress.org/akismet/trunk/akismet.php
>
> ======================================================
> function akismet_init() {
>        global $wpcom_api_key, $akismet_api_host, $akismet_api_port;
>
>        if ( $wpcom_api_key )
>                $akismet_api_host = $wpcom_api_key . '.rest.akismet.com';
>        else
>                $akismet_api_host = get_option('wordpress_api_key') . '.rest.akismet.com';
>
>        $akismet_api_port = 80;
> }
> add_action('init', 'akismet_init');
>
> ======================================================
>
> Why not just execute `akismet_init` directly? I can't see any drawback
> and sound not really useful to hook the init?
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers


More information about the wp-hackers mailing list