0
0
Wordpressframework~5 mins

Common 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. This helps you customize your site safely and easily.

You want to run code when WordPress starts loading.
You want to add content to the header or footer of your site.
You want to run code after a post is saved or updated.
You want to enqueue scripts and styles properly.
You want to add custom behavior when a user logs in or logs out.
Syntax
Wordpress
add_action('hook_name', 'your_function_name');

function your_function_name() {
    // Your code here
}

The first argument is the name of the action hook.

The second argument is the name of your function that runs when the hook fires.

Examples
This adds a custom meta tag inside the <head> section of your site.
Wordpress
add_action('wp_head', 'add_custom_meta');

function add_custom_meta() {
    echo '<meta name="custom" content="example">';
}
This starts a PHP session when WordPress initializes.
Wordpress
add_action('init', 'start_session');

function start_session() {
    if (!session_id()) {
        session_start();
    }
}
This runs code every time a post is saved or updated.
Wordpress
add_action('save_post', 'notify_on_save');

function notify_on_save($post_id) {
    // Code to notify admin when a post is saved
}
Sample Program

This code adds a friendly message at the bottom of every page on your WordPress site.

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; font-style:italic;">Thank you for visiting!</p>';
}
?>
OutputSuccess
Important Notes

Always use unique function names to avoid conflicts with other plugins or themes.

Use remove_action() if you want to stop a hook from running.

Action hooks do not return values; they just run code at certain points.

Summary

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

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

Common hooks include init, wp_head, wp_footer, and save_post.