working Custom Post Type and Widget code no longer works when moved from functions.php to plugin

If all you want is for your plugin to work, simply

replace

register_activation_hook( __FILE__, 'activate_my_careers' );

with

add_action( 'plugins_loaded', 'activate_my_careers' );

If you want to understand why your new plugin isn’t working, then you need to understand WordPress hooks. I would encourage you to carefully read the WordPress Plugin API.

The first hook available to (non- must-use) plugins is plugins_loaded. When I write plugins, the only thing I put into the main plugin file are adding actions to the activation, deactivation, and plugins_loaded hooks.

The function/method called by the plugins_loaded hook should load your plugin by adding actions and filters to other hooks. By using hooks you allow yourself and other plugins the option of removing those hooks before they fire. This makes your plugin extensible.

The key is to know which hooks fire when and to add functions/methods to specific hooks that only get fired when you want the function/method to be available.

So for your example, the only action we want to add when the main plugin file is included is a hook for plugins_loaded. The callback for that hook will then add the other actions needed for your plugin to work.

The reason your plugin isn’t working is because the activation hook is only fired immediately after a plugin is activated. Once the plugin is activated, the only other hook called is shutdown before you’re redirected to another page. From then on, the activation hook doesn’t fire and since it doesn’t none of your other actions will fire either.

Leave a Comment