Читать книгу Professional WordPress Plugin Development - Brad Williams - Страница 50

Plugin Activation Function

Оглавление

When building plugins, you'll often need to execute some code when the user first activates it. One common use case is adding custom capabilities to the administrator role (see Chapter 9, “Users and User Data”) for something like a custom post type (see Chapter 8, “Content”) that your plugin is registering. Or, you may need to set up a particular option for your plugin to perform.

WordPress provides the register_activation_hook() function that allows you to pass in a callback for handling any activation code you need to run.

<?php register_activation_hook( string $file, callable $function ); ?>

Parameters:

 $file (string, required): Filesystem path to the primary plugin file

 $function (callable, required): The PHP callable to be executed when the plugin is activated

It's generally best to separate your activation code from the rest of your plugin code simply for organizational purposes. The following example shows how to register an activation hook that points to a class located at src/Activation.php in your plugin and executes its activate() method:

<?php namespace PDEV; register_activation_hook( __FILE__, function() { require_once plugin_dir_path( __FILE__ ) . 'src/Activation.php'; Activation::activate(); } );

With the activation hook callback registered, you need to figure out what things you need to set upon activation. The following example gets the administrator role object and adds a custom capability to it:

<?php namespace PDEV; class Activation { public static function activate() { $role = get_role( 'administrator' ); if ( ! empty( $role ) ) { $role->add_cap( 'pdev_manage' ); } } }

There is no limit to what code you can run upon activation. It's a great time to run anything that needs to be set only once or things that shouldn't be run on every page load. For example, if your plugin needs to create custom database tables, this would be the time to do it.

While it is common practice with some plugin authors, you usually shouldn't set plugin database options at this point. It's almost always better to use sane defaults for any options your plugin has and not clutter the database until the end user has explicitly decided to save on your plugin settings screen (see Chapter 3).

Professional WordPress Plugin Development

Подняться наверх