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.


January 7, 2008 Posted by | Writing Plugins Series | , , | 1 Comment