In WordPress plugin development, hooks play a crucial role in extending and customizing the functionality of the platform. WordPress have two types of hooks.
- Action hooks – Action hooks allow you to execute custom functions at specific points in the WordPress lifecycle.
- Filter hooks – Filter hooks enable you to modify data.
Here are some of the most useful hooks for WordPress plugin development:
- Action Hooks:
admin_menu
: Used to add menu items to the admin dashboard.
// Example: Add a custom menu item to the admin dashboard
function custom_menu_item() {
add_menu_page('Custom Page', 'Custom Page', 'manage_options', 'custom-page', 'custom_page_callback');
}
add_action('admin_menu', 'custom_menu_item');
init
: Theinit
hook in WordPress is commonly used for initialization tasks.
// Example: Register a custom post type
function register_custom_post_type() {
register_post_type('custom_post', array(
'label' => 'Custom Post',
'public' => true,
// Add more arguments as needed
));
}
add_action('init', 'register_custom_post_type');
wp_enqueue_scripts
: Used to enqueue styles and scripts on the front end.
// Example: Enqueue a custom stylesheet
function enqueue_custom_styles() {
// Enqueue the style
wp_enqueue_style('custom-style', get_template_directory_uri() . '/css/custom-style.css', array(), '1.0.0', 'all');
}
add_action('wp_enqueue_scripts', 'enqueue_custom_styles');
// Example: Enqueue a custom script
function enqueue_custom_script() {
// Enqueue the script
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_script');
save_post
: Thesave_post
hook is triggered whenever a post or page is saved.
// Example: Update a custom field when a post is saved
function update_custom_field_on_save($post_id) {
// Check if this is an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the post type
$post_type = get_post_type($post_id);
if ($post_type != 'post') {
return;
}
// Update the custom field
$custom_field_value = get_post_meta($post_id, 'custom_field', true);
$new_custom_field_value = $custom_field_value . ' Updated!';
update_post_meta($post_id, 'custom_field', $new_custom_field_value);
}
add_action('save_post', 'update_custom_field_on_save');
wp_ajax_{action}
andwp_ajax_nopriv_{action}
: hooks are used for handling AJAX requests in WordPress. Thewp_ajax_{action}
hook is for authenticated users, whilewp_ajax_nopriv_{action}
is for non-authenticated users. Here’s an example:
// Example: Handle AJAX request for authenticated users
function my_ajax_handler() {
// Perform AJAX request handling here
$response = array(
'status' => 'success',
'message' => 'AJAX request successful!',
);
// Send the JSON response
wp_send_json($response);
}
// Hook for authenticated users
add_action('wp_ajax_my_action', 'my_ajax_handler');
// Example: Handle AJAX request for non-authenticated users
function my_ajax_handler_nopriv() {
// Perform AJAX request handling here for non-authenticated users
$response = array(
'status' => 'success',
'message' => 'AJAX request successful for non-authenticated users!',
);
// Send the JSON response
wp_send_json($response);
}
// Hook for non-authenticated users
add_action('wp_ajax_nopriv_my_action', 'my_ajax_handler_nopriv');
- Filter Hooks:
the_content
: Thethe_content
hook in WordPress allows you to modify the content of a post or page before it is displayed.
// Example: Modify the content of posts before display
function modify_content($content) {
return $content . '<p>This is added at the end of the content.</p>';
}
add_filter('the_content', 'modify_content');
the_title
: Thethe_title
hook in WordPress allows you to modify the title of a post or page before it is displayed.
// Example: Add a prefix to the post title
function add_prefix_to_title($title) {
// Check if it's a single post
if (is_single()) {
// Add a prefix to the title
$title = 'Prefix: ' . $title;
}
return $title;
}
// Hook into the_title
add_filter('the_title', 'add_prefix_to_title');
plugin_action_links_{plugin_file}
: Adds custom links to the plugin row on the plugins page.
// Example: Add custom links to the plugin row on the plugins page
function add_custom_plugin_links($links) {
// Add a link to the settings page
$settings_link = '<a href="' . admin_url('options-general.php?page=my-plugin-settings') . '">Settings</a>';
array_push($links, $settings_link);
// Add a link to the support forum
$support_link = '<a href="https://example.com/support-forum">Support</a>';
array_push($links, $support_link);
return $links;
}
// Hook into plugin_action_links_{plugin_file}
add_filter('plugin_action_links_my-plugin/my-plugin.php', 'add_custom_plugin_links');
wp_nav_menu_items
: Lets you add custom items to a navigation menu.
// Example: Add a custom menu item to the navigation menu
function add_custom_menu_item($items, $args) {
// Check if it's the primary navigation menu
if ($args->theme_location == 'primary') {
// Add a custom menu item
$custom_item = '<li class="menu-item custom-item"><a href="' . esc_url(home_url('/custom-page')) . '">Custom Page</a></li>';
$items .= $custom_item;
}
return $items;
}
// Hook into wp_nav_menu_items
add_filter('wp_nav_menu_items', 'add_custom_menu_item', 10, 2);
login_redirect
: Thelogin_redirect
hook allows you to customize the destination a user is redirected to after logging in.
// Example: Redirect users to a custom page after login
function custom_login_redirect($redirect_to, $request, $user) {
// Is there a user to check?
if (isset($user->roles) && is_array($user->roles)) {
// Check for admins
if (in_array('administrator', $user->roles)) {
// Redirect admins to the dashboard
return home_url('/admin-dashboard');
} else {
// Redirect other users to a custom page
return home_url('/custom-page');
}
} else {
// Redirect non-logged-in users to the default login page
return home_url('/login');
}
}
// Hook into login_redirect
add_filter('login_redirect', 'custom_login_redirect', 10, 3);
- Shortcode Hooks:
add_shortcode
: Allows you to create custom shortcodes for embedding functionality into posts and pages.
// Example: Create a custom shortcode to display a greeting
function greeting_shortcode() {
return 'Hello, welcome to my site!';
}
add_shortcode('greeting', 'greeting_shortcode');
- Widget Hooks:
widgets_init
: Used to register widgets and sidebars.
// Example: Register a custom widget
function register_custom_widget() {
register_widget('Custom_Widget_Class');
}
add_action('widgets_init', 'register_custom_widget');
- Custom Post Type Hooks:
register_post_type
: Allows you to create custom post types.
// Example: Register a custom post type
function register_custom_post_type() {
register_post_type('custom_post', array(
'label' => 'Custom Post',
'public' => true,
// Add more arguments as needed
));
}
add_action('init', 'register_custom_post_type');
manage_{post_type}_posts_custom_column
: Used to add custom columns to the post type admin screen.
- User and Login Hooks:
user_register
: Theuser_register
hook in WordPress is triggered when a new user is registered. You can use this hook to perform custom actions or execute additional logic when a new user account is created.
// Example: Send a welcome email when a new user registers
function send_welcome_email($user_id) {
$to = get_userdata($user_id)->user_email;
$subject = 'Welcome to My Site!';
$message = 'Thank you for registering on my site.';
wp_mail($to, $subject, $message);
}
add_action('user_register', 'send_welcome_email');
authenticate
: Used for custom authentication logic during the login process.
// Example: Custom authentication logic
function custom_authentication($user, $username, $password) {
// Check if the username and password are valid
if (is_wp_error($user)) {
return $user; // Invalid credentials, let WordPress handle it
}
// Perform additional custom authentication logic
$custom_validation = my_custom_authentication_function($username, $password);
if (!$custom_validation) {
// Authentication failed, create a custom error
$error = new WP_Error('authentication_failed', __('Invalid username or password.'));
return $error;
}
// Authentication successful, return the user
return $user;
}
// Hook into authenticate
add_filter('authenticate', 'custom_authentication', 10, 3);
// Example: Custom authentication logic function
function my_custom_authentication_function($username, $password) {
// Implement your custom authentication logic here
// For example, check against an external system, API, or database
// Return true if authentication succeeds, false otherwise
// For demonstration purposes, a simple example is provided
$valid_credentials = ($username === 'demo' && $password === 'password123');
return $valid_credentials;
}
wp_logout
: Thewp_logout
hook is triggered when a user logs out of WordPress. You can use this hook to perform custom actions or redirects after a user logs out.
// Example: Perform custom actions on user logout
function custom_logout_actions() {
// Add your custom logout actions here
// For example, you can log the logout event, redirect users, etc.
// In this example, we'll redirect users to the homepage after logout
wp_redirect(home_url());
exit();
}
// Hook into wp_logout
add_action('wp_logout', 'custom_logout_actions');
- Query Hooks:
pre_get_posts
: Thepre_get_posts
hook in WordPress allows you to modify the parameters of the main query before it is executed.
// Example: Show only custom post types on the homepage
function show_custom_post_types_on_homepage($query) {
if ($query->is_home() && $query->is_main_query()) {
$query->set('post_type', array('custom_post'));
}
}
add_action('pre_get_posts', 'show_custom_post_types_on_homepage');
- Cron Hooks:
wp_schedule_event
andwp_unschedule_event
: Used for scheduling and unscheduling cron jobs.
// Example: Schedule a daily cron job
function my_daily_cron_job() {
// Your cron job logic here
}
if (!wp_next_scheduled('my_daily_cron')) {
wp_schedule_event(time(), 'daily', 'my_daily_cron', 'my_daily_cron_job');
}
- Translation Hooks:
load_textdomain
: Allows you to load custom translations for your plugin.
// Example: Load custom translations for your plugin
function load_custom_translations() {
load_plugin_textdomain('my-plugin', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
add_action('plugins_loaded', 'load_custom_translations');
- REST API Hooks:
rest_api_init
: Used for adding custom routes and endpoints to the REST API.
// Example: Add a custom endpoint to the REST API
function custom_rest_api_endpoint() {
register_rest_route('custom/v1', '/data/', array(
'methods' => 'GET',
'callback' => 'custom_api_callback',
));
}
add_action('rest_api_init', 'custom_rest_api_endpoint');
- Customizer Hooks:
customize_register
: Allows you to add settings, controls, and sections to the Theme Customizer.
// Example: Add a custom setting to the Theme Customizer
function custom_customize_register($wp_customize) {
$wp_customize->add_setting('custom_setting', array(
'default' => '#000000',
'sanitize_callback' => 'sanitize_hex_color',
));
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'custom_setting', array(
'label' => __('Custom Color', 'text-domain'),
'section' => 'colors',
)));
}
add_action('customize_register', 'custom_customize_register');
These hooks provide a flexible and extensible framework for WordPress plugin development, allowing developers to customize and extend WordPress functionality according to their specific needs.