wp-content » themes » functions.php » WordPress hooks tutorial

WordPress hooks tutorial

WordPress hooks are a powerful feature that allows you to customize and extend the functionality of your WordPress website without modifying the core code. They are essentialy points in the WordPress code where you can add your own custom code or functions.

There are two types of hooks in WordPress: actions and filters. Action hooks allow you to add custom code or functions that execute at specific points in the WordPress code, while filter hooks allow you to modify data that is passed through the WordPress code.

Using hooks can be a great way to add custom functionality to your WordPress website, or to customize existing functionality without modifying the core code. This is particularly useful if you want to avoid losing your customizations when you update your WordPress site.

To use hooks in your WordPress site, you will need to add the appropriate hook function to your theme’s functions.php file or to a custom plugin. Here is an example of how to use an action hook to add a custom function to your WordPress site:

function my_custom_function() {
    // code to be executed when the hook is triggered
}
add_action('hook_name', 'my_custom_function');

In this example, the “hook_name” is the name of the action hook that you want to use, and the “my_custom_function” is the name of the function that you want to execute when the hook is triggered.

Here is an example of how to use a filter hook to modify data that is passed through the WordPress code:

function my_custom_function($data) {
    // modify $data as needed
    return $data;
}
add_filter('hook_name', 'my_custom_function');

In this example, the “hook_name” is the name of the filter hook that you want to use, and the “my_custom_function” is the name of the function that you want to use to modify the data. The modified data is then returned by the function.

There are hundreds of hooks available in WordPress, and they can be used to customize and extend your website in many different ways. Here are some of the most useful WordPress hooks that you can use to customize and extend your WordPress website:

WordPress hookWhere is executed?How can be used?
wp_headThis action hook is executed in the head section of the WordPress template.You can use this hook to add custom styles, scripts, or meta tags to the head of your website.
wp_footerThis action hook is executed in the footer section of the WordPress template.You can use this hook to add custom scripts or content to the footer of your website.
the_contentThis filter hook is used to modify the content of a post or page.You can use this hook to add custom content, modify the content, or remove content from the post or page.
the_titleThis filter hook is used to modify the title of a post or page.You can use this hook to add custom text, modify the title, or remove the title from the post or page.
pre_get_postsThis action hook is used to modify the main query before it is executed.You can use this hook to modify the query parameters, such as the post type, taxonomy, or order, to customize the content that is displayed on your website.
wp_enqueue_scriptsThis action hook is used to enqueue scripts and styles in the WordPress template.You can use this hook to add custom styles and scripts to your website.
login_formThis action hook is used to customize the login form.You can use this hook to add custom fields, modify the form, or redirect the user to a custom login page.

Simple WordPress hooks examples

By using hooks, you can customize and extend your WordPress website without modifying the core code, making it easier to update your site in the future.

Here are a few examples of how you can use WordPress hooks to customize and extend your WordPress website:

You can use the “login_form” action hook to add custom content or functionality to the WordPress login form. For example, you could add a custom message or a CAPTCHA to the login form to help prevent spam login attempts.

function my_custom_login_message() {
    echo '<p>Custom login message</p>';
}
add_action('login_form', 'my_custom_login_message');

In this example, the “login_form” action hook is used to execute the “my_custom_login_message” function when the login form is displayed. The function simply echoes a custom message, which will be displayed below the login form.


You can use the “widgets_init” action hook to register a custom widget for your WordPress site. This allows you to add a custom widget to your site’s sidebar or other widget-ready areas.

class My_Custom_Widget extends WP_Widget {
    // widget code goes here
}

function my_custom_widget_init() {
    register_widget('My_Custom_Widget');
}
add_action('widgets_init', 'my_custom_widget_init');

You can use the “excerpt_length” filter hook to modify the length of the excerpt that is displayed on your WordPress site. This allows you to control how much of each post is displayed in the excerpt.

function my_custom_excerpt_length($length) {
    return 20; // modify excerpt length as needed
}
add_filter('excerpt_length', 'my_custom_excerpt_length');

In this example, a custom widget class is created and then registered using the “widgets_init” action hook. The widget can then be added to any widget-ready area on the WordPress site (e.g., sidebar).


You can use the “excerpt_more” filter hook to customize the “read more” link that is displayed at the end of the excerpt on your WordPress site. This allows you to change the text or the link destination of the “read more” link.

function my_custom_excerpt_more($more) {
    return '<a href="' . get_permalink() . '">Read more</a>'; // modify the "read more" link as needed
}
add_filter('excerpt_more', 'my_custom_excerpt_more');

In this example, the “excerpt_more” filter hook is used to modify the “read more” link that is displayed at the end of the excerpt on the WordPress site. The “my_custom_excerpt_more” function returns a custom “read more” link, which will be displayed in place of the default link.


You can use the “manage_posts_columns” and “manage_posts_custom_column” action hooks to add a custom column to the posts screen in the WordPress dashboard. This allows you to display custom data for each post in the dashboard.

function my_custom_columns($columns) {
    $columns['custom_column'] = 'Custom Column';
    return $columns;
}
add_filter('manage_posts_columns', 'my_custom_columns');

function my_custom_column_content($column, $post_id) {
    if ($column == 'custom_column') {
        // display custom column content
    }
}
add_action('manage_posts_custom_column', 'my_custom_column_content');

In this example, the “manage_posts_columns” filter hook is used to add a custom column to the posts screen in the WordPress dashboard. The “my_custom_columns” function adds a new column called “Custom Column” to the list of columns. The “manage_posts_custom_column” action hook is then used to display the custom column content for each post.


function my_custom_welcome_panel() {
    echo '<p>Custom welcome panel content</p>';
}
add_action('welcome_panel', 'my_custom_welcome_panel');

In this example, the “welcome_panel” action hook is used to execute the “my_custom_welcome_panel” function when the welcome panel is displayed in the WordPress dashboard. The function simply echoes a custom message, which will be displayed in the welcome panel.


Customize the WordPress admin bar

function my_custom_admin_bar_menu($wp_admin_bar) {
    $wp_admin_bar->add_node(array(
        'id' => 'custom_node',
        'title' => 'Custom Node',
        'href' => 'https://www.example.com',
    ));
}
add_action('admin_bar_menu', 'my_custom_admin_bar_menu');

In this example, the “admin_bar_menu” action hook is used to add a custom node to the WordPress admin bar. The “my_custom_admin_bar_menu” function uses the “add_node” method to add a new node with a custom ID, title, and link destination.


Customize the WordPress search form

function my_custom_search_form($form) {
    $form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url('/') . '" >
    <div>
        <label class="screen-reader-text" for="s">' . __('Search for:') . '</label>
        <input type="text" value="' . get_search_query() . '" name="s" id="s" />
        <input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" />
    </div>
    </form>';

    return $form;
}
add_filter('get_search_form', 'my_custom_search_form');

In this example, the “get_search_form” filter hook is used to modify the default WordPress search form. The “my_custom_search_form” function returns a custom search form, which will be displayed in place of the default form.


Here are a few more advanced examples of WordPress hooks that you can use to customize and extend your WordPress website:

Customize the WordPress post editor

function my_custom_post_editor() {
    wp_enqueue_script('custom-post-editor', get_template_directory_uri() . '/js/custom-post-editor.js', array('jquery'), '1.0', true);
    wp_localize_script('custom-post-editor', 'custom_post_editor', array(
        'ajax_url' => admin_url('admin-ajax.php'),
    ));
}
add_action('admin_footer-post.php', 'my_custom_post_editor');
add_action('admin_footer-post-new.php', 'my_custom_post_editor');

In this example, the “admin_footer-post.php” and “admin_footer-post-new.php” action hooks are used to execute the “my_custom_post_editor” function when the post editor screen is displayed in the WordPress dashboard. The function enqueues a custom JavaScript file and localizes it with the “wp_localize_script” function, which allows you to pass data from the WordPress server to the JavaScript file.


Customize the WordPress media library

function my_custom_media_library($query) {
    $query['author'] = get_current_user_id();
}
add_filter('ajax_query_attachments_args', 'my_custom_media_library');

In this example, the “ajax_query_attachments_args” filter hook is used to modify the default WordPress media library query. The “my_custom_media_library” function adds a custom argument to the query, which filters the media library to only display media items uploaded by the current user.


Customize the WordPress user profile

function my_custom_user_profile($user) {
    ?>
    <h3>Custom User Profile Section</h3>
    <table class="form-table">
        <tr>
            <th><label for="custom_field">Custom Field</label></th>
            <td>
                <input type="text" name="custom_field" id="custom_field" value="<?php echo esc_attr(get_the_author_meta('custom_field', $user->ID)); ?>" class="regular-text" /><br />
                <span class="description">Enter a custom value for this field.</span>
            </td>
        </tr>
    </table>
    <?php
}
add_action('show_user_profile', 'my_custom_user_profile');
add_action('edit_user_profile', 'my_custom_user_profile');

function my_custom_user_profile_update($user_id) {
    if (!current_user_can('edit_user', $user_id)) {
        return;
    }

    update_user_meta($user_id, 'custom_field', sanitize_text_field($_POST['custom_field']));
}
add_action('personal_options_update', 'my_custom_user_profile_update');
add_action('edit_user_profile_update', 'my_custom_user_profile_update');

In this example, the “show_user_profile” and “edit_user_profile” action hooks are used to display a custom section in the WordPress user profile screen. The “my_custom_user_profile” function outputs a custom table row with a text input field. The “personal_options_update” and “edit_user_profile_update” action hooks are then used to save the custom field value when the user profile is updated.


Customize the WordPress REST API

function my_custom_rest_routes($routes) {
    $routes['/custom/route'] = array(
        array(
            'methods' => WP_REST_Server::READABLE,
            'callback' => 'my_custom_rest_route_callback',
        ),
    );

    return $routes;
}
add_filter('rest_api_routes', 'my_custom_rest_routes');

function my_custom_rest_route_callback($request) {
    // custom code goes here
}

In this example, the “rest_api_routes” filter hook is used to add a custom route to the WordPress REST API. The “my_custom_rest_routes” function adds a new route called “/custom/route”, which can be accessed using an HTTP GET request. The route is handled by the “my_custom_rest_route_callback” function, which can be used to return custom data or perform custom actions.


Customize the WordPress login process

function my_custom_login_redirect($redirect_to, $requested_redirect_to, $user) {
    if (is_a($user, 'WP_User')) {
        if (user_can($user, 'manage_options')) {
            return admin_url();
        } else {
            return home_url();
        }
    }

    return $redirect_to;
}
add_filter('login_redirect', 'my_custom_login_redirect', 10, 3);

In this example, the “login_redirect” filter hook is used to customize the WordPress login process. The “my_custom_login_redirect” function checks the user’s capabilities and returns a custom redirect URL based on the user’s role. For example, if the user is an administrator, they will be redirected to the WordPress dashboard; if the user is a subscriber, they will be redirected to the homepage.


Customize the WordPress password reset process

function my_custom_password_reset($user, $new_pass) {
    // custom code goes here
}
add_action('password_reset', 'my_custom_password_reset', 10, 2);

function my_custom_retrieve_password($user_login) {
    // custom code goes here
}
add_action('retrieve_password', 'my_custom_retrieve_password');

In this example, the “password_reset” action hook is used to execute the “my_custom_password_reset” function when a user’s password is reset. The function is passed two arguments: the user object and the new password. The “retrieve_password” action hook is also used to execute the “my_custom_retrieve_password” function when a user initiates the password reset process.


WooCommerce hooks examples

Most useful WooCommerce hooks that you can use to customize and extend your WooCommerce website are:

WooCommerce hookWhen is executed?How can be used?
woocommerce_checkout_processThis action hook is executed during the checkout process before the order is placed.You can use this hook to validate the checkout form fields and display custom error messages.
woocommerce_payment_completeThis action hook is executed when a payment is completed and the order is marked as “processing” or “completed”.You can use this hook to send custom emails, update custom fields, or perform any other custom actions.
woocommerce_order_status_changedThis action hook is executed whenever the order status is changed.You can use this hook to send custom emails or perform other custom actions based on the order status.
woocommerce_before_single_productThis action hook is executed before the single product template is loaded.You can use this hook to add custom content to the product page.
woocommerce_after_single_productThis action hook is executed after the single product template is loaded.You can use this hook to add custom content to the product page.
woocommerce_before_shop_loopThis action hook is executed before the shop loop (product list) is displayed.You can use this hook to add custom content to the shop page.
woocommerce_after_shop_loopThis action hook is executed after the shop loop (product list) is displayed.You can use this hook to add custom content to the shop page.

Here are a few examples of WordPress hooks that you can use to customize and extend your WooCommerce website:

Customize the WooCommerce cart page

function my_custom_cart_item_name($name, $cart_item, $cart_item_key) {
    // custom code goes here
    return $name;
}
add_filter('woocommerce_cart_item_name', 'my_custom_cart_item_name', 10, 3);

function my_custom_cart_item_price($price, $cart_item, $cart_item_key) {
    // custom code goes here
    return $price;
}
add_filter('woocommerce_cart_item_price', 'my_custom_cart_item_price', 10, 3);

function my_custom_cart_item_subtotal($subtotal, $cart_item, $cart_item_key) {
    // custom code goes here
    return $subtotal;
}
add_filter('woocommerce_cart_item_subtotal', 'my_custom_cart_item_subtotal', 10, 3);

In this example, the “woocommerce_cart_item_name”, “woocommerce_cart_item_price”, and “woocommerce_cart_item_subtotal” filter hooks are used to customize the cart page in WooCommerce. The “my_custom_cart_item_name” function modifies the product name, the “my_custom_cart_item_price” function modifies the product price, and the “my_custom_cart_item_subtotal” function modifies the product subtotal.

Here’s an example of how you can customize the WooCommerce cart page by modifying the product name, price, and subtotal:

function my_custom_cart_item_name($name, $cart_item, $cart_item_key) {
    $product = $cart_item['data'];
    $name .= '<br><small>Custom product attribute: ' . $product->get_attribute('custom_attribute') . '</small>';
    return $name;
}
add_filter('woocommerce_cart_item_name', 'my_custom_cart_item_name', 10, 3);

function my_custom_cart_item_price($price, $cart_item, $cart_item_key) {
    $product = $cart_item['data'];
    $price = '<del>' . wc_price($product->get_regular_price()) . '</del> <ins>' . wc_price($product->get_sale_price()) . '</ins>';
    return $price;
}
add_filter('woocommerce_cart_item_price', 'my_custom_cart_item_price', 10, 3);

function my_custom_cart_item_subtotal($subtotal, $cart_item, $cart_item_key) {
    $product = $cart_item['data'];
    $subtotal = wc_price($product->get_sale_price() * $cart_item['quantity']);
    return $subtotal;
}
add_filter('woocommerce_cart_item_subtotal', 'my_custom_cart_item_subtotal', 10, 3);

In this example, the “my_custom_cart_item_name” function adds a custom attribute to the product name, the “my_custom_cart_item_price” function displays the product’s sale price with strikethrough for the regular price.

Another example would be modifying the product name, price, and subtotal on the WooCommerce cart page:

function my_custom_cart_item_name($name, $cart_item, $cart_item_key) {
    $product = $cart_item['data'];
    $name .= '<br><small>Custom product attribute: ' . $product->get_attribute('custom_attribute') . '</small>';

    // Customize the product name based on the product's category
    $terms = get_the_terms($product->get_id(), 'product_cat');
    if ($terms && !is_wp_error($terms)) {
        $term = array_shift($terms);
        if ($term->slug == 'special') {
            $name .= '<br><strong>Special product!</strong>';
        }
    }

    return $name;
}
add_filter('woocommerce_cart_item_name', 'my_custom_cart_item_name', 10, 3);

function my_custom_cart_item_price($price, $cart_item, $cart_item_key) {
    $product = $cart_item['data'];

    // Customize the product price based on the customer's location
    $country = WC()->customer->get_billing_country();
    if ($country == 'US') {
        $price = wc_price($product->get_regular_price()) . ' (US price)';
    } elseif ($country == 'CA') {
        $price = wc_price($product->get_regular_price() * 1.15) . ' (Canadian price)';
    } else {
        $price = wc_price($product->get_regular_price()) . ' (International price)';
    }

    return $price;
}
add_filter('woocommerce_cart_item_price', 'my_custom_cart_item_price', 10, 3);

function my_custom_cart_item_subtotal($subtotal, $cart_item, $cart_item_key) {
    $product = $cart_item['data'];
    $subtotal = wc_price($product->get_sale_price() * $cart_item['quantity']);

    // Add a custom fee to the product subtotal
    $fee = 10;
    $subtotal += $fee;

    return $subtotal;
}
add_filter('woocommerce_cart_item_subtotal', 'my_custom_cart_item_subtotal', 10, 3);

In this example, the “my_custom_cart_item_name” function adds a custom attribute to the product name and also displays a message if the product belongs to the “special” category. The “my_custom_cart_item_price” function displays a customized price based on the customer’s location. The “my_custom_cart_item_subtotal” function calculates the product subtotal based on the sale price and quantity and then adds a custom fee to the subtotal.


Conclusion

In conclusion, WordPress hooks are a powerful and flexible feature that allows you to customize and extend your WordPress website without modifying the core code. They are an essential tool for WordPress developers and can be used to add custom functionality or modify existing functionality in a variety of ways.

To find the list of available hooks in WordPress, you can refer to the WordPress Codex or use a plugin like Plugin Dependencies, which allows you to see which hooks are being used by your installed plugins.

It’s important to note that using hooks correctly can require a certain level of knowledge and understanding of the WordPress codebase. If you are new to WordPress development, it may be helpful to start with simpler hooks and gradually work your way up to more complex ones.

Overall, WordPress hooks are a powerful and useful tool for WordPress developers, and by using them in conjunction with good SEO practices, you can create a highly customized and effective WordPress website.

Was this post helpful?

Leave a Comment

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.

Recommended