These functions let you add your own code to WordPress at specific points. They help you change or add features without changing WordPress core files.
0
0
add_action and add_filter in Wordpress
Introduction
You want to run your code when WordPress loads a page, like adding a message.
You want to change how WordPress shows content, like modifying post titles.
You want to add extra features to plugins or themes without editing their files.
You want to customize WordPress behavior safely during updates.
You want to run code after a user logs in or when a post is saved.
Syntax
Wordpress
add_action('hook_name', 'your_function_name', priority, accepted_args); add_filter('hook_name', 'your_function_name', priority, accepted_args);
add_action runs your function at a specific event.
add_filter changes data by passing it through your function.
Examples
This adds a message at the bottom of every page.
Wordpress
add_action('wp_footer', 'show_footer_message'); function show_footer_message() { echo '<p>Thanks for visiting!</p>'; }
This changes every post title by adding 'Hello:' before it.
Wordpress
add_filter('the_title', 'add_prefix_to_title'); function add_prefix_to_title($title) { return 'Hello: ' . $title; }
This runs your function early when WordPress starts.
Wordpress
add_action('init', 'custom_init_function', 10, 0); function custom_init_function() { // Code to run early in WordPress loading }
Sample Program
This code adds a blue welcome message centered in the footer of every page. It also adds a star before every post title.
Wordpress
<?php // Add a message to the footer add_action('wp_footer', 'footer_message'); function footer_message() { echo '<p style="text-align:center; color:blue;">Welcome to my site!</p>'; } // Change post titles by adding a star add_filter('the_title', 'star_title'); function star_title($title) { return '⭐ ' . $title; } ?>
OutputSuccess
Important Notes
Always use unique function names to avoid conflicts.
Priority controls the order your function runs; lower numbers run first.
Filters must return the modified data; actions do not return anything.
Summary
add_action lets you run code at specific WordPress events.
add_filter lets you change data before WordPress uses it.
Use these to customize WordPress safely without changing core files.