0
0
Wordpressframework~5 mins

Action hooks in Wordpress

Choose your learning style9 modes available
Introduction

Action hooks let you add your own code at specific points in WordPress without changing core files. They help you customize how WordPress works safely.

You want to run code when a post is published.
You want to add extra content to the footer of your site.
You want to send an email when a user registers.
You want to modify how WordPress loads scripts or styles.
You want to log information when a comment is posted.
Syntax
Wordpress
add_action('hook_name', 'your_function_name', priority, accepted_args);

function your_function_name() {
    // Your code here
}

hook_name is the name of the action point in WordPress.

priority controls the order your function runs (default is 10).

accepted_args is the number of arguments your function accepts (default is 1).

Examples
This adds a message at the bottom of every page in the footer.
Wordpress
add_action('wp_footer', 'add_footer_text');

function add_footer_text() {
    echo '<p>Thank you for visiting!</p>';
}
This runs when a post is published, with priority 20.
Wordpress
add_action('publish_post', 'notify_admin_on_publish', 20);

function notify_admin_on_publish($post_ID) {
    // Code to send email to admin
}
This runs when a new user registers, receiving the user ID as argument.
Wordpress
add_action('user_register', 'welcome_new_user', 10, 1);

function welcome_new_user($user_id) {
    // Send welcome email to new user
}
Sample Program

This code adds a centered gray message at the bottom of every page using the wp_footer action hook.

Wordpress
<?php
// Add a message to the footer
add_action('wp_footer', 'show_footer_message');

function show_footer_message() {
    echo '<p style="text-align:center; color: gray;">Powered by WordPress Action Hooks</p>';
}
?>
OutputSuccess
Important Notes

Action hooks do not change content directly; they let you run code at certain points.

Always use unique function names to avoid conflicts.

You can remove an action with remove_action() if needed.

Summary

Action hooks let you add custom code at specific points in WordPress.

Use add_action() with a hook name and your function.

They help customize WordPress safely without editing core files.