### Basic Theme Setup Example Source: https://developer.wordpress.org/reference/hooks/after_setup_theme A concise example for setting up essential theme features using the after_setup_theme hook. This snippet includes support for title tags, post thumbnails, post formats, HTML5 markup, and editor styles. ```php ``` -------------------------------- ### Twenty Fifteen Theme Setup Source: https://developer.wordpress.org/reference/hooks/after_setup_theme Example of theme setup using the after_setup_theme hook from the Twenty Fifteen default theme. This includes setting up text domains, feed links, title tags, post thumbnails, navigation menus, HTML5 support, post formats, custom backgrounds, and editor styles. ```php if ( ! function_exists( 'twentyfifteen_setup' ) ) :/** * Sets up theme defaults and registers support for various WordPress features. * * Note that this function is hooked into the after_setup_theme hook, which * runs before the init hook. The init hook is too late for some features, * such as indicating support for post thumbnails. * * @since Twenty Fifteen 1.0 */ function twentyfifteen_setup() { /* * Make theme available for translation. * Translations can be filed in the /languages/ directory. * If you're building a theme based on twentyfifteen, use a find and replace * to change 'twentyfifteen' to the name of your theme in all the template files */ load_theme_textdomain( 'twentyfifteen', get_template_directory() . '/languages' ); // Add default posts and comments RSS feed links to head. add_theme_support( 'automatic-feed-links' ); /* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded tag in the document head, and expect WordPress to * provide it for us. */ add_theme_support( 'title-tag' ); /* * Enable support for Post Thumbnails on posts and pages. * * See: https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails */ add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 825, 510, true ); // This theme uses wp_nav_menu() in two locations. register_nav_menus( array( 'primary' => __( 'Primary Menu', 'twentyfifteen' ), 'social' => __( 'Social Links Menu', 'twentyfifteen' ), ) ); /* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */ add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ) ); /* * Enable support for Post Formats. * * See: https://codex.wordpress.org/Post_Formats */ add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', 'gallery', 'status', 'audio', 'chat' ) ); $color_scheme = twentyfifteen_get_color_scheme(); $default_color = trim( $color_scheme[0], '#' ); // Setup the WordPress core custom background feature. add_theme_support( 'custom-background', apply_filters( 'twentyfifteen_custom_background_args', array( 'default-color' => $default_color, 'default-attachment' => 'fixed', ) ) ); /* * This theme styles the visual editor to resemble the theme style, * specifically font, colors, icons, and column width. */ add_editor_style( array( 'css/editor-style.css', 'genericons/genericons.css', twentyfifteen_fonts_url() ) ); } endif; // twentyfifteen_setup add_action( 'after_setup_theme', 'twentyfifteen_setup' ); ``` -------------------------------- ### Distinguish Plugin Installation vs. Upgrade Source: https://developer.wordpress.org/reference/hooks/upgrader_post_install This example demonstrates how to use the 'upgrader_post_install' filter to differentiate between a new plugin installation and an upgrade. It checks the 'destination_name' in the result and updates plugin options accordingly. ```php add_filter( 'upgrader_post_install', 'wpdocs_plugin_update', 10, 3 ); function wpdocs_plugin_update( $response, $extras, $result ) { if ( isset( $result['destination_name'] ) && 'wpdocs-plugin-slug' === $result['destination_name'] && $response ) { $my_settings = get_option( 'wpdocs-plugin-options', array() ); $my_settings['update'] = true; update_option( 'wpdocs-plugin-options', $my_settings ); } return $response; } ``` -------------------------------- ### Full Plugin Example with Update and Install Notices Source: https://developer.wordpress.org/reference/hooks/upgrader_process_complete A complete WordPress plugin that utilizes the upgrader_process_complete hook to display different notices upon plugin update or initial installation. It uses transients to manage the notice display state. ```php ' . __( 'Thanks for updating', 'wp-upe' ) . ''; delete_transient( 'wp_upe_updated' ); } } add_action( 'admin_notices', 'wp_upe_display_update_notice' ); /** * Show a notice to anyone who has just installed the plugin for the first time * This notice shouldn't display to anyone who has just updated this plugin */ function wp_upe_display_install_notice() { // Check the transient to see if we've just activated the plugin if( get_transient( 'wp_upe_activated' ) ) { echo '
' . __( 'Thanks for installing', 'wp-upe' ) . '
'; // Delete the transient so we don't keep displaying the activation message delete_transient( 'wp_upe_activated' ); } } add_action( 'admin_notices', 'wp_upe_display_install_notice' ); /** * Run this on activation * Set a transient so that we know we've just activated the plugin */ function wp_upe_activate() { set_transient( 'wp_upe_activated', 1 ); } register_activation_hook( __FILE__, 'wp_upe_activate' ); ``` -------------------------------- ### Example of load_textdomain usage Source: https://developer.wordpress.org/reference/hooks/load_textdomain This example demonstrates how to hook into the 'load_textdomain' action to log information about the translation file being loaded. It logs the file path and the text domain. ```php /** * Example of load_textdomain usage * @param string $domain Unique domain for translation. * @param string $mofile Path to the .mo file. * @param array|string $args Optional args used in taxonomy registration. */ function log_mo_file_load($domain, $mofile){ echo 'loading file "' . $mofile . '" on domain "' . $domain . '"'; // or whatever else you'd like to do here. } add_action( 'load_textdomain', 'log_mo_file_load' ); ``` -------------------------------- ### Start theme preview action Source: https://developer.wordpress.org/reference/hooks/start_previewing_theme Fires when the Customizer theme preview has started. Provides the WP_Customize_Manager instance. ```php do_action( 'start_previewing_theme', $this ); ``` -------------------------------- ### Example Usage of `current_screen` Hook Source: https://developer.wordpress.org/reference/hooks/current_screen This example demonstrates how to hook into the `current_screen` action to perform a specific action when editing a particular post type. ```php /** * Example of current_screen usage * @param $current_screen */ function wporg_current_screen_example( $current_screen ) { if ( 'someposttype' == $current_screen->post_type && 'post' === $current_screen->base ) { // Do something in the edit screen of this post type } } add_action( 'current_screen', 'wporg_current_screen_example' ); ``` -------------------------------- ### Custom Routing Based on GET Parameter Source: https://developer.wordpress.org/reference/hooks/template_include This example demonstrates how to implement custom routing by changing the template file based on the 'action' GET parameter. It defaults to 'address-list.php' if no specific action is matched. It's advisable to use a different variable for the new template and check if the file exists before returning it. ```php add_filter( 'template_include', 'wpdocs_include_template_files_on_page' ); function wpdocs_include_template_files_on_page( $template ) { $action = isset( $_GET['action'] ) ? $_GET['action'] : 'list'; switch ( $action ) { case 'add-list' : $template = __DIR__ . 'views/address-new.php'; break; case 'edit-list' : $template = __DIR__ . 'views/address-edit.php'; break; case 'view-list' : $template = __DIR__ . 'views/address-view.php'; break; default : $template = __DIR__ . 'views/address-list.php'; break; } return $template; } ``` -------------------------------- ### Example: Customizing Items Per Page with set-screen-option Source: https://developer.wordpress.org/reference/hooks/set-screen-option This example demonstrates how to use the `set-screen-option` filter to enforce a minimum and maximum value for a custom 'myitem_per_page' setting. It highlights the importance of hook priority for correct execution. ```php add_filter('set-screen-option', 'myFilterScreenOption', 10, 3); function myFilterScreenOption($keep, $option, $value) { if ($option === 'myitem_per_page') { if ($value < 0) { $value = 0; } elseif ($value > 100) { $value = 100; } } return $value; } ``` -------------------------------- ### Basic Authenticate Filter Example Source: https://developer.wordpress.org/reference/hooks/authenticate A simple example of how to hook into the 'authenticate' filter. This example passes the user object through without modification, allowing default WordPress authentication to proceed. ```php add_filter( 'authenticate', 'myplugin_auth_signon', 30, 3 ); function myplugin_auth_signon( $user, $username, $password ) { return $user; } ``` -------------------------------- ### Add User to Network Sites Example Source: https://developer.wordpress.org/reference/hooks/add_user_to_blog This example demonstrates how to add a newly registered user to multiple common sites across the network. It uses the 'user_register' hook to trigger the function and 'add_user_to_blog' to add the user to specified sites with a 'subscriber' role. ```php /** * Add a user to network sites. * * @param int $user_id User ID. */ function wpdocs_add_user_to_network_sites( $user_id ) { // Put common sites here $blogs = array( 1, 2, 3, 5,8 ); foreach ( $blogs as $blog ) { add_user_to_blog( $user_id, $blog, 'subscriber' ); } } add_action( 'user_register', 'wpdocs_add_user_to_network_sites' ); ``` -------------------------------- ### do_action( ‘wp_install’, WP_User $user ) Source: https://developer.wordpress.org/reference/hooks/wp_install Fires after a site is fully installed. This hook allows developers to execute custom functions when a new WordPress site is successfully installed. ```APIDOC ## do_action( ‘wp_install’, WP_User $user ) ### Description Fires after a site is fully installed. This hook allows developers to execute custom functions when a new WordPress site is successfully installed. ### Parameters #### Path Parameters * **$user** (WP_User) - The site owner. ### Source `wp-admin/includes/upgrade.php` ```php do_action( 'wp_install', $user ); ``` ``` -------------------------------- ### Define Custom Menu Order Example Source: https://developer.wordpress.org/reference/hooks/menu_order This example demonstrates how to define a custom menu order, placing Dashboard, Posts, and Comments at the beginning of the menu. Unmentioned menus will appear in their default relative order after these specified items. ```php add_filter( 'custom_menu_order', '__return_true' ); add_filter( 'menu_order', 'custom_menu_order' ); function custom_menu_order() { return array( 'index.php', 'edit.php', 'edit-comments.php' ); } ``` -------------------------------- ### apply_filters( ‘upgrader_post_install’, bool $response, array $hook_extra, array $result ) Source: https://developer.wordpress.org/reference/hooks/upgrader_post_install Filters the installation response after the installation has finished. This filter can be used to determine if a plugin is being installed for the first time or upgraded, allowing for version-specific actions. ```APIDOC ## apply_filters( ‘upgrader_post_install’, bool $response, array $hook_extra, array $result ) ### Description Filters the installation response after the installation has finished. ### Parameters * **$response** (bool) - Installation response. * **$hook_extra** (array) - Extra arguments passed to hooked filters. * **$result** (array) - Installation result data. ### Source `wp-admin/includes/class-wp-upgrader.php` ### Example Usage ```php add_filter( 'upgrader_post_install', 'wpdocs_plugin_update', 10, 3 ); function wpdocs_plugin_update( $response, $extras, $result ) { if ( isset( $result['destination_name'] ) && 'wpdocs-plugin-slug' === $result['destination_name'] && $response ) { $my_settings = get_option( 'wpdocs-plugin-options', array() ); $my_settings['update'] = true; update_option( 'wpdocs-plugin-options', $my_settings ); } return $response; } ``` ``` -------------------------------- ### Example: Handling Locale Switch with User Meta Update Source: https://developer.wordpress.org/reference/hooks/switch_locale This example demonstrates how to hook into the switch_locale action to update user meta with the new locale and display a confirmation message. It requires the user ID to be available. ```php // Define a callback function to execute when the switch_locale action is triggered function wpdocs_switch_locale_callback( $locale, $user_id ) { // Perform custom logic or tasks here based on the locale and user ID // Example: Update user meta with the new locale update_user_meta( $user_id, 'locale', $locale ); // Example: Display a success message echo 'Locale switched to: ' . $locale; } // Hook the callback function to the switch_locale action add_action( 'switch_locale', 'wpdocs_switch_locale_callback', 10, 2 ); ``` -------------------------------- ### do_action( “install_themes_{$tab}”, int $paged ) Source: https://developer.wordpress.org/reference/hooks/install_themes_tab Fires at the top of each of the tabs on the Install Themes page. The dynamic portion of the hook name, `$tab`, refers to the current theme installation tab. ```APIDOC ## do_action( “install_themes_{$tab}”, int $paged ) ### Description Fires at the top of each of the tabs on the Install Themes page. The dynamic portion of the hook name, `$tab`, refers to the current theme installation tab. Possible hook names include: * `install_themes_block-themes` * `install_themes_dashboard` * `install_themes_featured` * `install_themes_new` * `install_themes_search` * `install_themes_updated` * `install_themes_upload` ### Parameters `$paged` (int) Number of the current page of results being viewed. ### Source `wp-admin/theme-install.php` ``` -------------------------------- ### Example: Incrementing an Option Value Before Update Source: https://developer.wordpress.org/reference/hooks/pre_update_option_option This example demonstrates how to use the 'pre_update_option_foo' filter to intercept updates to the 'foo' option. It ensures the new value is an integer and increments it by one before saving. ```php add_action( 'init', 'myplugin_init' ); function myplugin_init() { add_filter( 'pre_update_option_foo', 'myplugin_update_field_foo', 10, 2 ); } function myplugin_update_field_foo( $new_value, $old_value ) { $new_value = intval( $new_value ); $new_value ++; return $new_value; } ``` -------------------------------- ### Example SQL Query for `posts_request` Source: https://developer.wordpress.org/reference/hooks/posts_request This is an example of the SQL query structure that the `posts_request` filter receives. It includes clauses for selecting posts, joining tables, filtering by ID and post type, and ordering results. ```sql SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts LEFT JOIN wp_posts AS p2 ON ( wp_posts.post_parent = p2.ID ) WHERE 1=1 AND wp_posts.ID IN ( 3, 632 ) AND wp_posts.post_type != 'revision' AND ( ( wp_posts.post_status = 'publish' ) OR ( wp_posts.post_status = 'inherit' AND ( p2.post_status = 'publish' ) ) ) ORDER BY wp_posts.post_date DESC LIMIT 0, 20 ``` -------------------------------- ### Plugin Data Structure Example Source: https://developer.wordpress.org/reference/hooks/after_plugin_row This example shows the typical structure of the `$plugin_data` array passed to the 'after_plugin_row' hook. It includes various details about a plugin, such as its slug, version, author, and compatibility information. ```php array ( 'id' => string '' (length=0), 'slug' => string '' (length=0), 'plugin' => string '' (length=0), 'new_version' => string '1.4.10' (length=6), 'url' => string '' (length=0), 'package' => string '' (length=0), 'icons' => array (size=2) '2x' => string '' (length=0) '1x' => string '' (length=0), 'banners' => array (size=1) '1x' => string '' (length=0), 'banners_rtl' => array (size=0) empty, 'tested' => string '5.5.3' (length=5), 'requires_php' => boolean false, 'compatibility' => object(stdClass)[1022], 'update-supported' => boolean true, 'Name' => string '' (length=0), 'PluginURI' => string '' (length=0), 'Version' => string '1.4.9' (length=5), 'Description' => string '' (length=0), 'Author' => string '' (length=0), 'AuthorURI' => string '' (length=0), 'TextDomain' => string '' (length=0), 'DomainPath' => string '/languages' (length=10), 'Network' => boolean false, 'RequiresWP' => string '' (length=0), 'RequiresPHP' => string '' (length=0), 'Title' => string '' (length=0), 'AuthorName' => string '' (length=0), 'update' => boolean true ) ``` -------------------------------- ### Customize Press This Bookmarklet Link for Custom Post Type Source: https://developer.wordpress.org/reference/hooks/shortcut_link This example shows how to use the 'shortcut_link' filter to create a 'Press This' button for a custom post type named 'example'. It modifies the link to include the custom post type and adjusts query parameter separators. ```PHP add_filter('shortcut_link', 'press_this_ptype', 11); function press_this_ptype($link) { $post_type = 'example'; $link = str_replace('post-new.php', "post-new.php?post_type=$post_type", $link); $link = str_replace('?u=', '&u=', $link); return $link; } ``` -------------------------------- ### Example $hook_extra Parameter Data Source: https://developer.wordpress.org/reference/hooks/upgrader_process_complete This example shows the structure of the $hook_extra parameter passed to the upgrader_process_complete hook, specifically for a plugin update action. It details the action, type, bulk status, and the list of plugins being updated. ```php Array ( [action] => update [type] => plugin [bulk] => 1 [plugins] => Array ( [0] => wordpress-beta-tester/wp-beta-tester.php ) ) ``` -------------------------------- ### Basic Admin Initialization Action Source: https://developer.wordpress.org/reference/hooks/admin_init A simple example demonstrating how to hook a function to the admin_init action to perform an action, such as echoing text, when the admin screen initializes. ```php /** * Fire on the initialization of the admin screen or scripts. */ function the_dramatist_fire_on_admin_screen_initialization() { // Do stuff. Say we will echo "Hello World". echo 'Hello World'; } add_action( 'admin_init', 'the_dramatist_fire_on_admin_screen_initialization' ); ``` -------------------------------- ### apply_filters( ‘install_plugin_complete_actions’, string[] $install_actions, object $api, string $plugin_file ) Source: https://developer.wordpress.org/reference/hooks/install_plugin_complete_actions Filters the list of action links available following a single plugin installation. This filter is applied after a plugin has been successfully installed, allowing for modification of the links presented to the user, such as 'Activate' or 'View details'. ```APIDOC ## Function Signature apply_filters( ‘install_plugin_complete_actions’, string[] $install_actions, object $api, string $plugin_file ) ### Description Filters the list of action links available following a single plugin installation. ### Parameters #### Parameters - **$install_actions** (string[]) - Required - Array of plugin action links. - **$api** (object) - Required - Object containing WordPress.org API plugin data. Empty for non-API installs, such as when a plugin is installed via upload. - **$plugin_file** (string) - Required - Path to the plugin file relative to the plugins directory. ### Source `wp-admin/includes/class-plugin-installer-skin.php` ```php $install_actions = apply_filters( 'install_plugin_complete_actions', $install_actions, $this->api, $plugin_file ); ``` ``` -------------------------------- ### Sending a welcome email on first login Source: https://developer.wordpress.org/reference/hooks/wp_login This example demonstrates how to send a personalized welcome email to a user upon their first successful login. It checks if the user is an administrator or if the welcome email has already been sent to prevent duplicates. ```php // callback function function wpdocs_send_welcome_email( $user_login, WP_User $user ) { // do not send email if user has already logged in once if ( current_user_can( 'administrator' ) || get_user_meta( $user->ID, 'wpdocs_welcome_email_sent', TRUE ) ) { return; } // send welcome email if logging in first time $message = str_replace( array( '%%firstname%%', '%%name%%', '%%sitename%%' ), array( $user->first_name, $user->data->user_login, get_bloginfo( 'name' ), ), get_option( 'welcome_message' ) ); // send email to user if ( wp_mail( $user->data->user_email, 'Welcome subject', $message ) ) { // update or add user meta if email sent successfully update_user_meta( $user->ID, 'wpdocs_welcome_email_sent', 1 ); } } // action hook add_action( 'wp_login', 'wpdocs_send_welcome_email', 10, 2 ); ``` -------------------------------- ### Get IDs of multiple posts being restored Source: https://developer.wordpress.org/reference/hooks/untrash_post This example shows how to retrieve the IDs of multiple posts when they are being restored from the Trash using the 'untrash_post' hook. It handles both single and multiple post restoration scenarios. ```php function wpdocs_untrash_multiple_posts( $post_id = '' ) { // Verify if is restoring multiple posts if ( isset( $_GET['post'] ) && is_array( $_GET['post'] ) ) { foreach( $_GET['post'] as $post_id ) { wpdocs_your_function( $post_id ); } } else { wpdocs_your_function( $post_id ); } } add_action( 'untrash_post', 'wpdocs_untrash_multiple_posts' ); ``` -------------------------------- ### Using wp_initialize_site instead of wp_insert_site Source: https://developer.wordpress.org/reference/hooks/wp_insert_site This example demonstrates how to use the wp_initialize_site hook with a high priority to perform actions after a site is fully set up, as wp_insert_site may fire too early for certain operations. ```php add_action( 'wp_initialize_site', 'wpdocs_action_wp_initialize_site', 900 ); /** * Fires when a site's initialization routine should be executed. * * @param WP_Site $new_site New site object. */ function wpdocs_action_wp_initialize_site( WP_Site $new_site ) : void { switch_to_blog( $new_site->blog_id ); // do the job restore_current_blog(); } ``` -------------------------------- ### Override Comment Form Reply Title Source: https://developer.wordpress.org/reference/hooks/comment_form_defaults An example of overriding the default 'Leave a Reply' title for the comment form. This code can be placed in a theme's functions.php file within the theme setup function. ```php function wpdocs_comment_form_defaults( $defaults ) { $defaults['title_reply'] = __( 'Add a Comment' ); return $defaults; } add_filter( 'comment_form_defaults', 'wpdocs_comment_form_defaults' ); ``` -------------------------------- ### wp_untrash_post_status Source: https://developer.wordpress.org/reference/hooks/wp_untrash_post_status Filters the status that a post gets assigned when it is restored from the trash (untrashed). By default, restored posts are assigned a status of 'draft'. This filter allows you to change that behavior, for example, to assign the status the post had before it was trashed. ```APIDOC ## apply_filters( ‘wp_untrash_post_status’, string $new_status, int $post_id, string $previous_status ) ### Description Filters the status that a post gets assigned when it is restored from the trash (untrashed). By default, restored posts are assigned a status of ‘draft’. Return the value of `$previous_status` in order to assign the status that the post had before it was trashed. The `wp_untrash_post_set_previous_status()` function is available for this. Prior to WordPress 5.6.0, restored posts were always assigned their original status. ### Parameters #### Parameters * **$new_status** (string) - The new status of the post being restored. * **$post_id** (int) - The ID of the post being restored. * **$previous_status** (string) - The status of the post at the point where it was trashed. ### Source `wp-includes/post.php` ```php $post_status = apply_filters( 'wp_untrash_post_status', $new_status, $post_id, $previous_status ); ``` ``` -------------------------------- ### Change Locale Based on URL Parameter Source: https://developer.wordpress.org/reference/hooks/locale This example demonstrates how to change the WordPress locale dynamically based on a 'language' GET parameter in the URL. It returns 'ka_GL' for Greenlandic if the parameter is 'gl', otherwise it returns the original locale. ```php ``` -------------------------------- ### Store Previous and Current Plugin Versions Source: https://developer.wordpress.org/reference/hooks/upgrader_pre_install This example demonstrates how to use 'upgrader_pre_install' and 'upgrader_process_complete' to store the previous and current versions of a specific plugin. This is useful for debugging or rollback purposes. ```php Welcome to this site. Please log in to continue

"; } else { return $message; } } add_filter( 'login_message', 'the_login_message' ); ``` -------------------------------- ### Customizing Sitemap Index Home URL in Multisite Source: https://developer.wordpress.org/reference/hooks/wp_sitemaps_index_entry This example demonstrates how to alter the home URL for the sitemap index in a WordPress Multisite setup using the 'wp_sitemaps_index_entry' filter. It ensures that the sitemap links correctly point to the main site's home URL. ```php add_filter( 'wp_sitemaps_index_entry', 'wpdocs_sitemaps_index_entry_callback' ); function wpdocs_sitemaps_index_entry_callback( $sitemap_entry ) { switch_to_blog( get_blog_id_from_url( $_SERVER['HTTP_HOST'] ) ); $link_array = explode( '/', $sitemap_entry['loc'] ); $sitemap_url_element = end( $link_array ); $sitemap_entry['loc'] = home_url( $sitemap_url_element ); return $sitemap_entry; } ``` -------------------------------- ### Split theme.json into Multiple Files Source: https://developer.wordpress.org/reference/hooks/wp_theme_json_data_theme This example demonstrates how to split the 'theme.json' configuration into multiple files (e.g., 'theme-styles.json' and 'theme-settings.json') and then merge them back together. Ensure the 'version' is set to 3 or higher. ```PHP function wpdocs_compose_theme_json( $theme_json ) { // Load sub files $theme_styles_raw = file_get_contents( get_template_directory() . '/theme-styles.json' ); $theme_settings_raw = file_get_contents( get_template_directory() . '/theme-settings.json' ); // Convert JSON to array $theme_styles = json_decode( $theme_styles_raw, true ); $theme_settings = json_decode( $theme_settings_raw, true ); // Inject data $new_data = [ 'version' => 3, // Mandatory, or it won’t work 'settings' => $theme_settings['settings'], 'styles' => $theme_styles['styles'], ]; // Update WordPress' theme.json return $theme_json->update_with( $new_data ); } add_filter( 'wp_theme_json_data_theme', 'wpdocs_compose_theme_json' ); ``` ```JSON { "$schema": "https://schemas.wp.org/trunk/theme.json", "settings": { "color": {} } } ``` -------------------------------- ### Add User URL to Search Columns (Codex Example) Source: https://developer.wordpress.org/reference/hooks/user_search_columns This is a Codex example showing how to add the 'user_url' field to the columns searched. It is functionally identical to another example but presented separately. ```php add_filter( 'user_search_columns', 'filter_function_name', 10, 3 ); function filter_function_name( $search_columns, $search, $wp_user_query ) { $search_columns[] = 'user_url'; return $search_columns; } ``` -------------------------------- ### Instantiate Class Method on Load Source: https://developer.wordpress.org/reference/hooks/plugins_loaded This example demonstrates how to call an instance method of a class when plugins are loaded. The class uses a singleton pattern to ensure only one instance is created. ```php add_action( 'plugins_loaded', array( 'wpdocs_class_name', 'instance' ) ); class wpdocs_class_name { private function __construct() { self::init(); } public static function instance() { static $instance = null; if ( is_null( $instance ) ) { $instance = new class_name; } return $instance; } public function init() { wp_die( __( 'Hello World!', 'text-domain' ) ); } } ``` -------------------------------- ### Filtering Package Installation Result Source: https://developer.wordpress.org/reference/hooks/upgrader_install_package_result This snippet shows how to apply a filter to modify the result of a package installation. It's used within the WP_Upgrader class to allow for custom actions based on the installation outcome. ```php $result = apply_filters( 'upgrader_install_package_result', $result, $options['hook_extra'] ); ``` -------------------------------- ### Conditionally Search User URL for '.com' Terms (Codex Example) Source: https://developer.wordpress.org/reference/hooks/user_search_columns This Codex example conditionally searches only the 'user_url' field if the search term contains '.com'. It is functionally identical to another example but presented separately. ```php add_filter( 'user_search_columns', 'filter_function_name', 10, 3 ); function filter_function_name( $search_columns, $search, $wp_user_query ) { $val = strpos($search, '.com'); if( $val !== false ) { $search_columns = array('user_url'); } return $search_columns; } ``` -------------------------------- ### Fire Action on WordPress Initialization Source: https://developer.wordpress.org/reference/hooks/init This example demonstrates how to hook into the 'init' action to execute custom code during WordPress's initialization phase. It echoes a message to confirm execution. ```php /** * Fire on the initialization of WordPress. */ function the_dramatist_fire_on_wp_initialization() { // Do stuff. Say we will echo "Fired on the WordPress initialization". echo 'Fired on the WordPress initialization'; } add_action( 'init', 'the_dramatist_fire_on_wp_initialization' ); ``` -------------------------------- ### Allow JavaScript Protocol (Use with Caution) Source: https://developer.wordpress.org/reference/hooks/kses_allowed_protocols This example demonstrates how to allow the 'javascript' protocol. Due to security risks, this should be used with extreme caution and only when absolutely necessary, as it can enable cross-site scripting (XSS) vulnerabilities. ```PHP add_filter( 'kses_allowed_protocols', function( $protocols ) { $protocols[] = 'javascript'; return $protocols; } ); ``` -------------------------------- ### do_action( ‘network_plugin_loaded’, string $network_plugin ) Source: https://developer.wordpress.org/reference/hooks/network_plugin_loaded Fires once a single network-activated plugin has loaded. It passes the full path to the plugin's main file as an argument. ```APIDOC ## do_action( ‘network_plugin_loaded’, string $network_plugin ) ### Description Fires once a single network-activated plugin has loaded. ### Parameters #### Path Parameters - **$network_plugin** (string) - Required - Full path to the plugin’s main file. ### Source `wp-settings.php` ``` -------------------------------- ### Basic User Authentication Filter Example Source: https://developer.wordpress.org/reference/hooks/wp_authenticate_user A simple example of how to hook into wp_authenticate_user for custom login validation. It passes through the user object by default. ```php add_filter('wp_authenticate_user', 'myplugin_auth_login',10,2); function myplugin_auth_login ($user, $password) { //do any extra validation stuff here return $user; } ``` -------------------------------- ### pre_get_blogs_of_user Filter Example Source: https://developer.wordpress.org/reference/hooks/pre_get_blogs_of_user This is an example of how the pre_get_blogs_of_user filter is applied within the WordPress core. It demonstrates the hook's signature and how it's called. ```php $sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all ); ``` -------------------------------- ### Log Warnings with a Class Source: https://developer.wordpress.org/reference/hooks/admin_notices This example demonstrates an object-oriented approach to displaying warning messages. Initialize the class with a message to hook it into 'admin_notices'. ```php /** * Class to log warnings. */ class Log_Warning { /** * Message to be displayed in a warning. * * @var string */ private string $message; /** * Initialize class. * * @param string $message Message to be displayed in a warning. */ public function __construct( string $message ) { $this->message = $message; add_action( 'admin_notices', array( $this, 'render' ) ); } /** * Displays warning on the admin screen. * * @return void */ public function render() { printf( '

Warning: %s

', esc_html( $this->message ) ); } } new Log_Warning( 'Image should contain async tag' ); ``` -------------------------------- ### Example Usage of quick_edit_custom_box Source: https://developer.wordpress.org/reference/hooks/quick_edit_custom_box This is an example of how the 'quick_edit_custom_box' action hook is called within the WordPress core. It passes the column name, post type, and taxonomy as arguments. ```php do_action( 'quick_edit_custom_box', $column_name, $screen->post_type, '' ); ``` -------------------------------- ### do_action( ‘pre-upload-ui’ ) Source: https://developer.wordpress.org/reference/hooks/pre-upload-ui Fires just before the legacy (pre-3.5.0) upload interface is loaded. ```APIDOC ## do_action( 'pre-upload-ui' ) ### Description Fires just before the legacy (pre-3.5.0) upload interface is loaded. ### Method Action Hook ### Endpoint N/A (WordPress Hook) ### Source `wp-admin/includes/media.php` ### Usage Example ```php do_action( 'pre-upload-ui' ); ``` ### Related - **media_upload_form()**: Outputs the legacy media upload form. - **wp_print_media_templates()**: Prints the templates used in the media manager. ``` -------------------------------- ### Enqueue Customizer Preview Script (Alternative) Source: https://developer.wordpress.org/reference/hooks/customize_preview_init An alternative PHP example for enqueuing a script for the Theme Customizer's live preview. This version uses `get_theme_file_uri` and registers the script before enqueuing. ```php function wpdocs_enqueue_customize_preview_script() { $theme = wp_get_theme(); wp_register_script( 'wpdocs-cript', get_theme_file_uri( 'js/script.js' ), array( 'jquery', 'customize-preview' ), $theme->get( 'Version' ), ); wp_enqueue_script( 'wpdocs-script' ); } add_action( 'customize_preview_init', 'wpdocs_enqueue_customize_preview_script' ); ``` -------------------------------- ### Example Usage of edit_term Hook Source: https://developer.wordpress.org/reference/hooks/edit_term This example demonstrates how to hook into the 'edit_term' action to perform custom actions, such as updating term meta, specifically for the 'category' taxonomy. ```php function wp_edit_term_example( $term_id, $tt_id, $taxonomy ) { // Return if it is not default taxonomy if ( 'category' !== $taxonomy ) { return; } // Get term data by term id and taxonomy $term = get_term( $term_id, $taxonomy ); // Update term meta update_term_meta( $term_id, '_term_example_meta_key', 'term_example_meta_value' ); } add_action( 'edit_term', 'wp_edit_term_example', 10, 3 ); ``` -------------------------------- ### Execute wpmu_options Hook Source: https://developer.wordpress.org/reference/hooks/wpmu_options Fires at the end of the Network Settings form, before the submit button. ```php do_action( 'wpmu_options' ); ``` -------------------------------- ### Example: Protecting Custom Meta Fields Source: https://developer.wordpress.org/reference/hooks/is_protected_meta This example demonstrates how to use the is_protected_meta filter to protect two custom meta fields, 'my_first_meta' and 'my_second_meta', by setting them as protected. ```php function my_meta_is_protected_meta( $protected, $meta_key, $meta_type ) { switch ($meta_key) { case 'my_first_meta': $protected = true; break; case 'my_second_meta': $protected = true; break; } return $protected; } add_filter( 'is_protected_meta', 'my_meta_is_protected_meta', 10, 3 ); ``` -------------------------------- ### Wrap oEmbed HTML with Provider-Specific Classes Source: https://developer.wordpress.org/reference/hooks/embed_oembed_html A more robust method to wrap oEmbed HTML, adding specific classes like 'vimeo' or 'youtube' along with a general 'responsive-container' class. This is recommended over the previous example. ```php add_filter( 'embed_oembed_html', 'wpse_embed_oembed_html', 99, 4 ); function wpse_embed_oembed_html( $cache, $url, $attr, $post_ID ) { $classes = array(); // Add these classes to all embeds. $classes_all = array( 'responsive-container', ); // Check for different providers and add appropriate classes. if ( false !== strpos( $url, 'vimeo.com' ) ) { $classes[] = 'vimeo'; } if ( false !== strpos( $url, 'youtube.com' ) ) { $classes[] = 'youtube'; } $classes = array_merge( $classes, $classes_all ); return '' . $cache . ''; } ``` -------------------------------- ### Example Usage of delete_attachment Hook Source: https://developer.wordpress.org/reference/hooks/delete_attachment This example demonstrates how to hook into the delete_attachment action to perform custom logic before an attachment is deleted. It retrieves the file path and name of the attachment. ```php function wpdocs_delete_attachment( $post_id ) { // Do something before attachment deleted // get attached file dir $file = get_attached_file( $post_id ); // get file name of attachment to be deleted $file_name = wp_basename( $file ); } add_action( 'delete_attachment', 'wpdocs_delete_attachment' ); ``` -------------------------------- ### Apply upgrader_post_install Filter Source: https://developer.wordpress.org/reference/hooks/upgrader_post_install This snippet shows how the 'upgrader_post_install' filter is applied within the WP_Upgrader class. It passes the installation response, hook extra arguments, and the result of the installation. ```php $res = apply_filters( 'upgrader_post_install', true, $args['hook_extra'], $this->result ); ``` -------------------------------- ### Filter Plugin Install Actions Source: https://developer.wordpress.org/reference/hooks/install_plugin_complete_actions This code snippet shows how to apply a filter to modify the action links displayed after a plugin installation. It is used within the Plugin_Installer_Skin class. ```php $install_actions = apply_filters( 'install_plugin_complete_actions', $install_actions, $this->api, $plugin_file ); ``` -------------------------------- ### Enable Subdirectory Installation Feature Source: https://developer.wordpress.org/reference/hooks/allow_subdirectory_install This snippet shows how to use the `allow_subdirectory_install` filter to enable the subdirectory installation feature in WordPress Multisite. It is a boolean filter that defaults to false. ```php if ( apply_filters( 'allow_subdirectory_install', false ) ) { } ``` -------------------------------- ### apply_filters( ‘signup_site_meta’, array $meta, string $domain, string $path, string $title, string $user, string $user_email, string $key ) Source: https://developer.wordpress.org/reference/hooks/signup_site_meta Filters the metadata for a site signup. The metadata will be serialized prior to storing it in the database. ```APIDOC ## apply_filters( ‘signup_site_meta’, array $meta, string $domain, string $path, string $title, string $user, string $user_email, string $key ) ### Description Filters the metadata for a site signup. The metadata will be serialized prior to storing it in the database. ### Parameters * **$meta** (array) - Signup meta data. Default empty array. * **$domain** (string) - The requested domain. * **$path** (string) - The requested path. * **$title** (string) - The requested site title. * **$user** (string) - The user’s requested login name. * **$user_email** (string) - The user’s email address. * **$key** (string) - The user’s activation key. ### Source `wp-includes/ms-functions.php` ```php $meta = apply_filters( 'signup_site_meta', $meta, $domain, $path, $title, $user, $user_email, $key ); ``` ``` -------------------------------- ### Apply the 'the_guid' filter Source: https://developer.wordpress.org/reference/hooks/the_guid This snippet shows how to apply the 'the_guid' filter to a post's GUID. It is used within WordPress core to modify the GUID before it's output. ```php echo apply_filters( 'the_guid', $post_guid, $post_id ); ```