--- name: wp-plugin-development description: "Architecture and development guidelines for WordPress plugins published on wordpress.org: file structure, plugin header, lifecycle hooks, Settings API, admin UI, escaping helpers for admin JavaScript, default values and option migrations, translatable defaults, multisite-shared resources, short-circuit filters, custom post types, custom database tables, internationalization, plugin dependencies, readme.txt and changelog rules, and wordpress.org submission and release requirements. Use it whenever you create or restructure a plugin, add settings, hooks, post types or tables, make a plugin translation-ready, or prepare a release or a wordpress.org submission. Based on the official WordPress Plugin Developer Handbook and Plugin Review Team guidelines." compatibility: "WordPress 6.0+ / PHP 7.4+. Targets plugins for distribution on wordpress.org." license: GPL-2.0-or-later metadata: author: fernando-tellado version: "1.4" --- # WordPress plugin development ## When to use Use this skill when: - Creating a new WordPress plugin from scratch - Preparing a plugin for submission to wordpress.org - Structuring plugin files and folders - Implementing activation, deactivation, or uninstall routines - Building admin settings pages with the Settings API - Registering custom post types or taxonomies - Creating custom database tables - Making a plugin translation-ready - Handling plugin dependencies (required plugins or PHP extensions) - Reviewing code before wordpress.org submission ## Core development principles ### The plugin development mantra ``` Use WordPress APIs, never reinvent the wheel Prefix everything, conflict with nothing Clean up after yourself on uninstall Leave no trace when disabled ``` ### Key concepts 1. **Prefix everything**: All functions, classes, constants, and options must use a unique prefix to avoid conflicts 2. **WordPress APIs first**: Use WordPress functions over native PHP whenever an API exists 3. **Lifecycle awareness**: Know what runs on activation, deactivation, and uninstall — and keep them separate 4. **Settings API**: Never save options by hand; use the Settings API to register, validate, and store settings 5. **GPL compatibility**: All code and bundled libraries must be GPL-compatible for wordpress.org 6. **No inline assets**: Never print '; } // WRONG: Inline style printed with PHP add_action( 'wp_head', 'myplugin_bad_inline_style' ); function myplugin_bad_inline_style() { echo ''; } // CORRECT: External JS file with data passed via wp_localize_script wp_enqueue_script( 'myplugin-frontend', MYPLUGIN_URL . 'assets/js/frontend.js', array(), MYPLUGIN_VERSION, true ); wp_localize_script( 'myplugin-frontend', 'mypluginConfig', array( 'api' => 'https://example.com', ) ); // CORRECT: External CSS file wp_enqueue_style( 'myplugin-frontend', MYPLUGIN_URL . 'assets/css/frontend.css', array(), MYPLUGIN_VERSION ); // CORRECT: Small dynamic CSS via wp_add_inline_style (requires a registered stylesheet) $custom_color = sanitize_hex_color( get_option( 'myplugin_color', '#333' ) ); wp_add_inline_style( 'myplugin-frontend', ".myplugin-widget { color: {$custom_color}; }" ); // CORRECT: Small dynamic JS via wp_add_inline_script (requires a registered script) wp_add_inline_script( 'myplugin-frontend', 'console.log("loaded");', 'after' ); ``` The only acceptable way to add small amounts of dynamic CSS or JS is through `wp_add_inline_style()` and `wp_add_inline_script()`, which attach the code to a properly enqueued handle. ### Plugin header requirements for wordpress.org | Field | Required | Notes | |-------|----------|-------| | `Plugin Name` | Yes | Unique, descriptive | | `Description` | Yes | Max 150 characters recommended | | `Version` | Yes | Semantic versioning (1.0.0) | | `Requires at least` | Yes | Minimum WordPress version | | `Requires PHP` | Yes | Minimum PHP version | | `Author` | Yes | Your name or company | | `License` | Yes | Must be GPL-2.0-or-later or compatible | | `Text Domain` | Yes | Must match the plugin folder slug | | `Domain Path` | Deprecated | Do not add this line | | `Tested up to` | Optional | Normally declared only in `readme.txt`. If the plugin header declares it as well, the header value overrides the readme and Plugin Check requires both to match (`mismatched_tested_up_to_header`), so updating it stops being a readme-only change | | `Requires Plugins` | Optional (WP 6.5+) | Comma-separated plugin slugs that must be active before this plugin activates. WordPress prompts the user to install/activate them. Older WP versions ignore the header silently, so it is safe to declare even on plugins that target 6.0+. | | `WC requires at least` | WooCommerce add-ons only | Minimum WooCommerce version. Recognised by WC itself, not by WordPress core. | | `WC tested up to` | WooCommerce add-ons only | Latest WooCommerce version you tested against. | ## Plugin lifecycle ### Activation hook Runs when the plugin is activated. Use it to create database tables, set default options, and schedule cron events. **Careful with anything you write outside your own tables and options.** Activation runs with `activate_plugins`, which on a multisite network the network administrator can delegate to every subsite administrator with a native checkbox (Network Settings, Menu Settings, Plugins). If activation writes `wp-config.php`, the root `.htaccess` or the root `robots.txt`, one site is rewriting what the whole network reads, and the plugin may not even be active on the sites that suffer it. Gate those writes with `is_multisite() ? current_user_can( 'manage_network_options' ) : current_user_can( 'manage_options' )`, and prefer the virtual route when WordPress offers one: the `robots_txt` filter is per site, the physical file is not. ```php // CORRECT: Activation - set up what the plugin needs to run public static function activate() { // Check capabilities - prevents direct URL activation exploits if ( ! current_user_can( 'activate_plugins' ) ) { return; } // Create custom tables self::create_tables(); // Set default options (only if they don't exist yet) if ( false === get_option( 'myplugin_settings' ) ) { add_option( 'myplugin_settings', array( 'enabled' => true, 'limit' => 10, ), '', 'yes' ); // 'yes' = autoload } // Schedule cron events if ( ! wp_next_scheduled( 'myplugin_daily_task' ) ) { wp_schedule_event( time(), 'daily', 'myplugin_daily_task' ); } // Store plugin version for future upgrade checks update_option( 'myplugin_version', MYPLUGIN_VERSION ); // Flush rewrite rules if registering CPTs flush_rewrite_rules(); } // WRONG: Never run heavy logic or queries during activation without guards public static function activate() { $results = $wpdb->get_results( "SELECT * FROM {$wpdb->posts}" ); // Never! wp_remote_get( 'https://api.example.com/register' ); // Never! } ``` ### Deactivation hook Runs when the plugin is deactivated. Clean up temporary data and scheduled events. Do NOT delete user data here. ```php // CORRECT: Deactivation - stop scheduled tasks, clear transients public static function deactivate() { if ( ! current_user_can( 'activate_plugins' ) ) { return; } // Remove scheduled cron events wp_clear_scheduled_hook( 'myplugin_daily_task' ); // Clear transients delete_transient( 'myplugin_cache' ); // Flush rewrite rules (remove CPT slugs from .htaccess) flush_rewrite_rules(); // WRONG: Do NOT delete options or tables here - that is uninstall logic } ``` ### Uninstall logic Runs only when the user deletes the plugin. This is where you permanently remove all plugin data. ```php // OPTION A: uninstall.php in the plugin root (recommended for complex cleanup) query( "DROP TABLE IF EXISTS {$wpdb->prefix}myplugin_data" ); // Delete all plugin transients $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_myplugin\_%' OR option_name LIKE '\_transient\_timeout\_myplugin\_%'" ); // OPTION B: register_uninstall_hook() in main file (for simple cleanup only) // register_uninstall_hook( MYPLUGIN_FILE, 'myplugin_uninstall' ); // Note: uninstall.php takes precedence over register_uninstall_hook() ``` ### Path detection in `uninstall.php` The Plugin Review Team flags any combination of `WP_PLUGIN_DIR` with a hardcoded slug literal as "hardcoded plugin folder path". It does not matter if the code is conceptually correct (e.g. detecting a legacy parallel install); the reviewer will reject it. ```php // REJECTED: even though it would work, the linter flags the slug literal. $canonical = trailingslashit( WP_PLUGIN_DIR ) . 'my-plugin'; if ( __DIR__ !== untrailingslashit( $canonical ) && is_dir( $canonical ) ) { return; } // ACCEPTED: derive the path from __FILE__ instead. $plugin_dir = plugin_dir_path( __FILE__ ); // or use __DIR__ ``` If you genuinely need a safeguard for legacy installation folders (e.g. users who downloaded a GitHub source ZIP before the canonical wordpress.org release existed), document the upgrade path in the FAQ instead and let the standard install/uninstall flow handle it. ### Lifecycle comparison | Hook | When it runs | Use for | |------|-------------|---------| | `register_activation_hook` | On activation click | Create tables, default options, schedule cron | | `register_deactivation_hook` | On deactivation click | Clear cron, flush rewrites, delete transients | | `uninstall.php` | On plugin deletion | Delete all options, tables, user meta | | `plugins_loaded` | Every request, after plugins load | Initialize plugin classes | | `init` | Every request | Register CPTs, taxonomies, shortcodes | ### Defaults are product decisions, and sometimes security decisions The value a plugin ships with is the value almost every install will run forever. Two consequences that are easy to miss: - **A protection that ships disabled protects nobody.** In one audited plugin the correct reverse-DNS verification of search engine bots was written, working and switched off by default, while the feature it was supposed to secure was switched on: the "private site" mode opened for anyone sending `User-Agent: Googlebot`. The code was right, the default was the vulnerability. - **Changing a default does not reach existing installs.** If activation persisted the whole defaults array into an option, `wp_parse_args()` will never restore the new value, because the old one is stored. The change only affects fresh installs unless you migrate. ```php // Migrate with a version option, never with a transient: a transient expires and // the routine runs again, which is how a user's deliberate choice gets overwritten. if ( (int) get_option( 'myplugin_settings_version', 0 ) < 2 ) { $settings = get_option( 'myplugin_settings', array() ); if ( is_array( $settings ) && empty( $settings['verify_bots'] ) ) { $settings['verify_bots'] = true; update_option( 'myplugin_settings', $settings ); } update_option( 'myplugin_settings_version', 2 ); } ``` Say it in the changelog too. A default that flips is a behaviour change, and users who relied on the old one deserve to read about it before they update rather than after. ## Main plugin class Use a singleton to avoid multiple instantiations and keep global state controlled. ```php load_dependencies(); $this->define_hooks(); } /** * Load required files. */ private function load_dependencies(): void { require_once MYPLUGIN_DIR . 'includes/class-my-plugin-admin.php'; require_once MYPLUGIN_DIR . 'includes/class-my-plugin-public.php'; require_once MYPLUGIN_DIR . 'includes/class-my-plugin-cpt.php'; } /** * Register all action and filter hooks. */ private function define_hooks(): void { $admin = new My_Plugin_Admin(); $public = new My_Plugin_Public(); $cpt = new My_Plugin_CPT(); // Admin hooks add_action( 'admin_menu', array( $admin, 'add_admin_menu' ) ); add_action( 'admin_init', array( $admin, 'register_settings' ) ); add_action( 'admin_enqueue_scripts', array( $admin, 'enqueue_assets' ) ); // Public hooks add_action( 'wp_enqueue_scripts', array( $public, 'enqueue_assets' ) ); add_shortcode( 'my_plugin', array( $public, 'render_shortcode' ) ); // CPT and taxonomy registration add_action( 'init', array( $cpt, 'register_post_types' ) ); add_action( 'init', array( $cpt, 'register_taxonomies' ) ); } /** * Activation callback (called from register_activation_hook in main file). */ public static function activate(): void { // Activation logic here flush_rewrite_rules(); } /** * Deactivation callback. */ public static function deactivate(): void { wp_clear_scheduled_hook( 'myplugin_daily_task' ); flush_rewrite_rules(); } } ``` ## Hooks system ### Actions vs filters ```php // ACTION: do something at a point in execution (no return value needed) add_action( 'save_post', 'myplugin_on_save_post', 10, 2 ); function myplugin_on_save_post( int $post_id, WP_Post $post ): void { // Do something when a post is saved } // FILTER: modify a value and return it (always return the value!) add_filter( 'the_content', 'myplugin_filter_content', 10, 1 ); function myplugin_filter_content( string $content ): string { // Modify and always return return $content . '
Added by plugin
'; } // WRONG: Forgetting to return in a filter breaks the site add_filter( 'the_content', function( $content ) { echo $content; // Never echo in a filter! // No return = null is returned, content disappears } ); ``` ### Hook priorities ```php // Default priority is 10. Lower = earlier, higher = later. add_action( 'init', 'myplugin_early_init', 5 ); // Runs before default add_action( 'init', 'myplugin_normal_init' ); // Priority 10 (default) add_action( 'init', 'myplugin_late_init', 20 ); // Runs after default // Number of accepted arguments (4th parameter) add_action( 'save_post', 'myplugin_handler', 10, 3 ); // $post_id, $post, $update ``` ### Removing hooks ```php // To remove a hook added with a named function remove_action( 'wp_head', 'wp_generator' ); // To remove a hook added with a class method - needs same instance $instance = My_Plugin::get_instance(); remove_action( 'init', array( $instance, 'some_method' ) ); // WRONG: This does not work for anonymous functions (no reference) $fn = function() { /* ... */ }; add_action( 'init', $fn ); remove_action( 'init', $fn ); // Works only if $fn is still in scope ``` ### Filters that depend on a specific call site Some filters only fire in a specific code path. The most common pitfall: `shortcode_atts_{tag}` only fires when WordPress calls `shortcode_atts()` from inside `do_shortcode()`. If the same render function is invoked directly from another context (a custom WooCommerce endpoint, a Gutenberg block render callback, a REST response, an `admin_post_*` handler), the filter never runs. ```php // WRONG: The filter only applies when the form is rendered via [my_form] shortcode. // Calling my_render_form() from a WC endpoint silently skips the prefill. add_filter( 'shortcode_atts_my_form', 'my_prefill_from_query' ); function my_prefill_from_query( $atts ) { if ( isset( $_GET['order_id'] ) ) { $atts['order_id'] = sanitize_text_field( wp_unslash( $_GET['order_id'] ) ); } return $atts; } // CORRECT: Extract the logic to a helper that both call sites invoke. function my_get_prefill_order_id() { // ... nonce check + sanitize + return value ... return $order_id; } // Endpoint caller passes the value directly: function my_account_endpoint_content() { my_render_form( array( 'order_id' => my_get_prefill_order_id(), ) ); } // Shortcode caller goes through the filter, which uses the same helper: add_filter( 'shortcode_atts_my_form', function( $atts ) { $order_id = my_get_prefill_order_id(); if ( '' !== $order_id ) { $atts['order_id'] = $order_id; } return $atts; } ); ``` Same pattern applies to any filter named after a specific hook context: `the_content` filters do not run on raw post body access, `the_title` does not run on `get_the_title()` in some admin contexts, etc. When in doubt, extract the logic and call it from every entry point. ### Short-circuit filters: answering early is the opposite of being polite Some core filters are short-circuits: when the filter returns a value, core uses it and skips its own work (`pre_get_document_title`, `pre_option_*`, `pre_http_request`). Every callback hooked there still runs, in priority order, and the last one has the final say unless it hands back what it received. So on those filters priority is not courtesy. It decides who wins. A plugin hooked `pre_get_document_title` at priority 5 "so as not to get in the way". A popular theme hooked the same filter at the default priority, and the first statement of its callback emptied the incoming value. On every site with that theme the custom title never reached `' . esc_html__( 'Configure the general plugin behavior.', 'my-plugin' ) . '
'; } /** * Render the "enabled" checkbox field. */ public function render_field_enabled(): void { $value = $this->get( 'enabled' ); printf( '', esc_attr( self::OPTION_NAME ), checked( $value, true, false ) ); echo ''; } /** * Render the "limit" number field. */ public function render_field_limit(): void { $value = $this->get( 'limit' ); printf( '', esc_attr( self::OPTION_NAME ), absint( $value ) ); echo '' . esc_html__( 'Number of results to show (1-100).', 'my-plugin' ) . '
'; } } ``` ### Admin menu and settings page ```php /** * Registers admin menu pages. * Hooked to admin_menu. */ public function add_admin_menu(): void { // Top-level menu page add_menu_page( __( 'My Plugin', 'my-plugin' ), // Page title __( 'My Plugin', 'my-plugin' ), // Menu title 'manage_options', // Capability required 'myplugin-settings', // Menu slug array( $this, 'render_settings_page' ), // Callback 'dashicons-admin-generic', // Icon 80 // Position ); // Submenu page (can also add submenus under existing menus) add_submenu_page( 'myplugin-settings', // Parent slug __( 'My Plugin Settings', 'my-plugin' ), // Page title __( 'Settings', 'my-plugin' ), // Menu title 'manage_options', 'myplugin-settings', array( $this, 'render_settings_page' ) ); } /** * Render the settings page. * settings_fields() and do_settings_sections() do all the heavy lifting. */ public function render_settings_page(): void { // Always check capabilities again before rendering if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission to access this page.', 'my-plugin' ) ); } ?>' . sprintf( /* translators: %s: plugin name */ esc_html__( 'My Plugin requires %s to be installed and active.', 'my-plugin' ), 'WooCommerce' ) . '
' . sprintf( /* translators: %s: comma-separated list of PHP extensions */ esc_html__( 'My Plugin requires the following PHP extensions: %s', 'my-plugin' ), '' . esc_html( implode( ', ', $missing_extensions ) ) . '' ) . '