WordPress | Action Hooks

WordPress Action Hooks

When building or customizing a WordPress site, hooks are your best friend. They allow you to extend or modify WordPress behavior without touching its core files. Hooks come in two types — actions and filters(we’ll see filter hooks in the next blog).

What are Action Hooks in WordPress?

Action hooks let you add or execute custom code at specific points. The following are some useful and commonly used WordPress action hooks, which can be placed in the functions.php file of your theme without directly modifying core WordPress files.

Hire WordPress Developer

List of Action Hooks in WordPress:

Some useful Action hooks are:

wp_head():

You might want to insert custom meta information (like description, author name, or keywords) into your site’s <head> for SEO or analytics purposes — without editing your theme’s header file.

Code:

add_action('wp_head', 'mytheme_add_custom_meta_tags');
function mytheme_add_custom_meta_tags() {
    if (is_single()) {
        global $post;
        $meta_description = esc_attr(wp_trim_words(strip_tags($post->post_content), 25));
        $meta_author = esc_attr(get_the_author_meta('display_name', $post->post_author));
        $meta_keywords = wp_get_post_tags($post->ID, array('fields' => 'names'));
        if (!empty($meta_keywords)) {
            $meta_keywords = esc_attr(implode(', ', $meta_keywords));
        }
        echo "<meta name='description' content='{$meta_description}' />\n";
        echo "<meta name='author' content='{$meta_author}' />\n";
        if (!empty($meta_keywords)) {
            echo "<meta name='keywords' content='{$meta_keywords}' />\n";
        }
    }
}
wp_head

You might want to add a simple functionality like Scroll to Top, you can use this hook to insert its script with its html and styles, which will add a simple scroll to top button at the bottom right.

Code:

add_action('wp_footer', 'mytheme_add_back_to_top_button');
function mytheme_add_back_to_top_button()
{
    ?>
    <style>
        #backToTop {
            position: fixed;
            bottom: 25px;
            right: 25px;
            display: none;
            background-color: #333;
            color: #fff;
            border: none;
            border-radius: 50%;
            width: 45px;
            height: 45px;
            font-size: 22px;
            cursor: pointer;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            z-index: 9999;
        }

        #backToTop:hover {
            background-color: #0073aa;
            /* WordPress blue tone */
            transform: translateY(-4px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.25);
        }

        #backToTop.show {
            display: flex;
            align-items: center;
            justify-content: center;
            animation: fadeIn 0.4s ease forwards;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: scale(0.8);
            }

            to {
                opacity: 1;
                transform: scale(1);
            }
        }
    </style>

    <button id="backToTop" aria-label="Back to top">↑</button>

    <script>
        const btn = document.getElementById('backToTop');
        window.addEventListener('scroll', () => {
            if (window.scrollY > 300) {
                btn.classList.add('show');
            } else {
                btn.classList.remove('show');
            }
        });
        btn.addEventListener('click', () => window.scrollTo({
            top: 0,
            behavior: 'smooth'
        }));
    </script>
<?php
}
wp_footer

customize_register():

Useful for adding theme customization options like colors, text, or toggles without building a custom settings page in your Customize page, which is at Appearance → Customize. In this example, I have added a simple checkbox for toggle functionality

Code:

add_action('customize_register', 'mytheme_customize_topbar');
function mytheme_customize_topbar($wp_customize)
{
    // Add a new section for header/topbar controls
    $wp_customize->add_section('mytheme_header_topbar_section', [
        'title'       => __('Header & Topbar Settings', 'mytheme'),
        'priority'    => 30,
        'description' => __('Control the visibility and appearance of your topbar.', 'mytheme'),
    ]);

    // Add the toggle setting
    $wp_customize->add_setting('show_topbar', [
        'default'           => true,
        'sanitize_callback' => 'wp_validate_boolean',
    ]);

    // Add checkbox control
    $wp_customize->add_control('show_topbar', [
        'label'    => __('Display Topbar', 'mytheme'),
        'section'  => 'mytheme_header_topbar_section',
        'type'     => 'checkbox',
        'description' => __('Enable or disable the topbar above your main header.', 'mytheme'),
    ]);
}
customize_register

admin_notices():

Use this to alert admins about missing configurations, plugin updates, or critical site issues.

Here, I will show you three different types of admin notices you can use.

Code:

add_action('admin_notices', 'mytheme_demo_admin_notices');
	function mytheme_demo_admin_notices()
	{
    	// Success message
   	 echo '<div class="notice notice-success is-dismissible">
        	<p><strong>Success:</strong> Your settings have been saved successfully.</p>
    	</div>';

    	// Warning message
    	echo '<div class="notice notice-warning is-dismissible">
        	<p><strong>Warning:</strong> You are currently running WP_DEBUG mode. It is 	recommended to disable it on live sites.</p>
    	</div>';

    	// Error message
   	 echo '<div class="notice notice-error is-dismissible">
        	<p><strong>Error:</strong> Failed to connect to the external API. Please check your 	credentials.</p>
    	</div>';
	}
admin_notices

wp_login():

You can log user login times, IPs, or actions for analytics or security purposes.

Code:

add_action('wp_login', 'mytheme_record_login', 10, 2);
	function mytheme_record_login($user_login, $user) {
    		update_user_meta($user->ID, 'last_login_time', current_time('mysql'));
    		update_user_meta($user->ID, 'last_login_ip', $_SERVER['REMOTE_ADDR']);
	}

wp_enqueue_scripts():

To load custom scripts and styles in the right way instead of hardcoding them in the theme files. You can confirm your script and stylesheet are properly enqueued by checking your browser’s Developer Tools → Network or Elements tab, viewing the page source, or adding a simple console.log() test inside your JS file. For example, I have enqued my Swiper.js assets in this example.

Code:

function mg_theme_enqueue_scripts()
	{
    	// Enqueue Swiper assets
    	wp_enqueue_style('swiper', 'https://unpkg.com/swiper/swiper-bundle.min.css', [], '8.4.5');
   	 wp_enqueue_script('swiper', 'https://unpkg.com/swiper/swiper-bundle.min.js', [], '8.4.5', 		true);
    
    	}
	add_action('wp_enqueue_scripts', 'mg_theme_enqueue_scripts');

admin_enqueue_scripts():

Used when your custom admin page, metabox, or plugin settings require extra JS or CSS.

This is the same as the wp_enqueue_scripts() function, but the only difference is, this function is used only for admin panel pages you create.

Code:

add_action('admin_enqueue_scripts', 'mytheme_load_admin_scripts');
	function mytheme_load_admin_scripts($hook) {
   	 	if ('settings_page_mytheme-settings' === $hook) {
        		wp_enqueue_style('wp-color-picker');
        		wp_enqueue_script('mytheme-admin-js', get_template_directory_uri() . 			'/admin/js/admin.js', ['wp-color-picker'], '1.0', true);
    	}
}

admin_init():

You can register settings, add user capabilities, or perform security verification before the admin pages load.

Code:

add_action('admin_init', 'mytheme_restrict_admin_access');
	function mytheme_restrict_admin_access()
	{
    		if (!current_user_can('administrator') && !wp_doing_ajax()) {
        		wp_redirect(home_url());
        		exit;
    		}
	}

As you can see, I was logged as a subscriber, but when I tried to access the wp-admin, I was redirected to a non-admin page.

Conclusion

WordPress action hooks provide a method for developers to enhance functionality easily and safely. Action hooks allow developers to write more modular, maintainable, and flexible code that easily interacts with WordPress core files as well as other plugins or themes.

Whether you want to add custom content, initiate automated functions, or extend admin functionality, learning how action hooks work in WordPress is imperative for any serious WordPress developer.

FAQ

1. What is the purpose of an action hook in WordPress?

Action hooks give developers the ability to run their custom functions at certain points of WordPress execution without editing core files.

2. Where should I place my action hook code?

You can place it in your theme’s functions.php file or in a custom plugin.

3. Are WordPress action hooks safe to use?

Yes, action hooks are completely safe and a great way to enhance functionality for WordPress, because you do not modify core files.

Previous Article

How to Get Abandoned Checkout using GraphQL API in Shopify Remix App?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨