Function Documentation

WordPress Function Documentation Progress

Writing Plugins: Put all logic in functions

The only code that should be outside functions are the hooks into activate, deactivate, and init hook. A plugin should not assume that it can put HTML and echo blocks outside of functions, because the HTML and logic will display before WordPress is initiated.

The explanation for this is the plugins are included into the process after all of the WordPress library files are included, but before the rest of WordPress is set up. The reason to hook into the ‘init’ hook is that is when WordPress is finished setting everything up and is called at the very end of the wp-setting.php file.

Every plugin should have this code structure:

function mynamespace_init() {
    // hook into all needed filters and actions
}

add_action('init', 'mynamespace_init');

What You Should Never Do

  1. if( WordPress is Setup ) {
        echo "I'm evil
    "; }

    This will always fail, because there is no way to figure out if WordPress is ready for output without using the Plugin API.


  2. require ( ABSPATH . WPINC . '/plugins.php' );

    This will cause WordPress to fail since plugins.php is already included at the time your plugin is included. You should never include WordPress library files! The exception to this might be the admin library files, but you should always check for the function you want before trying to include the file and should always check the inclusion path inside the admin page you’ll be hooking into.

Advertisements

January 7, 2008 - Posted by | Writing Plugins Series | , ,

1 Comment »

  1. […] all means, ignore this suggestion, because this does not apply to you. For all of the others, the suggestion to put logic in functions […]

    Pingback by Writing Plugins: Writing Maintainable Procedural Plugins « Function Documentation | January 22, 2008 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: