If you’ve ventured into the world of WordPress development, you’ve undoubtedly encountered the term “hooks, but what are they? WordPress hooks are the key to unlocking WordPress’s full potential and we gathered them in a handy WordPress hooks list for you to use.
Think of hooks as the ultimate toolkit for developers. It’s the secret ingredient that turns a standard WordPress site into a bespoke masterpiece. These hooks are the vital links that allow you to inject custom functionality, alter core behaviors, and tailor every aspect of your site to your precise needs.
Understanding and leveraging WordPress hooks opens up a realm of possibilities, enabling you to craft unique, powerful, and personalized WordPress experiences.
It represents the very backbone of WordPress’s flexibility and extendibility, and is pivotal to the platform’s architecture, allowing developers to customize and extend WordPress functionality in ways that align perfectly with their project needs, all while avoiding the pitfalls of modifying core files.
What are WordPress Hooks?
In WordPress, a hook is a mechanism that lets you add your custom code or modify WordPress’s default behavior. There are two main types of hooks:
- Actions: These allow you to execute the code at specific points during the WordPress runtime. For example, you can use an action to create a custom widget when WordPress initializes or send a notification when a new post is published.
- Filters: These enable you to modify the data before it is sent to the database or browser. Filters are useful for tasks like altering the content displayed in posts or adjusting how excerpts are shown.
How WordPress Hooks Help With WordPress Coding
1. Unmatched Customization and Flexibility
Hooks offer unparalleled customization power, allowing you to tailor WordPress precisely to your needs. You can add or modify features seamlessly, without touching the core WordPress files. This flexibility empowers you to create websites that meet the requirements and adapt to varied preferences.
2. Superior Maintainability
One of the standout benefits of using hooks is the separation of custom code from core WordPress files. This separation ensures that your customizations remain intact even after WordPress updates. It simplifies the update process, minimizes conflict risks, and streamlines ongoing maintenance.
3. Optimized Performance
Hooks allow you to execute custom code only when necessary, leading to improved site performance. By attaching functions to specific actions or filters, you avoid running redundant code, thus optimizing resource use and enhancing site speed.
4. Efficient Code Reusability
WordPress hooks promote modular and reusable code. You can craft functions for specific tasks and then attach them to various hooks as needed. This modular approach keeps your code organized and enables you to repurpose functions across different projects, saving both time and effort.
5. Cleaner Codebase
Using hooks helps maintain a cleaner, more organized codebase in the WordPress dashboard. Instead of scattering custom modifications throughout your theme or plugin files, encapsulate these changes within functions and attach them to the appropriate hooks. This method makes your code more readable, easier to debug, and simpler to maintain.
6. Streamlined Development
Hooks simplify development by providing predefined points for inserting custom code. This ease of use is especially beneficial for implementing complex functionalities, as you can hook into specific points in the WordPress lifecycle without delving into the core code.
7. Robust Community Support
The vibrant WordPress community actively leverages and supports hooks. With abundant resources such as documentation, tutorials, and forums, you have access to invaluable support for learning and effectively implementing WordPress hooks. This community backing is crucial for overcoming challenging customization tasks.
8. Effortless Plugin and Theme Integration
Hooks enable smooth integration with a vast array of plugins and themes. You can extend or modify their functionality using WordPress hooks without directly altering their files. This ensures that updates to plugins and themes do not overwrite your customizations, preserving compatibility and minimizing potential issues. Get your hands on the latest WordPress themes with blazing fast speed here.
Actions vs. Filters: A Comparative Overview
Let’s start by understanding the key differences between WordPress Actions and Filters with the help of a detailed table:
Aspect | Actions | Filters |
---|---|---|
Purpose | Actions are used to run custom functions at specific points during the execution of WordPress Core | Filters are used to modify or customize data used by other functions |
Definition | Actions are defined/created by the function do_action( ‘action_name’ ) in the WordPress code | Filters are defined/created by the function apply_filters( ‘filter_name’, ‘value_to_be_filtered’ ) in the WordPress code |
Also Known As | Action hooks | Filter hooks |
Hook Functions | Actions can only be hooked in with Action functions. Examples: add_action() , remove_action() | Filters can only be hooked in with Filter functions. Examples: add_filter() , remove_filter() |
Arguments | Action functions need not pass any arguments to their callback functions | Filter functions need to pass at least one argument to their callback functions |
Function Tasks | Action functions can perform any kind of task, including changing the behavior of how WordPress works | Filter functions only exist to modify the data passed to them by the filters. Action functions should return nothing. However, they can echo the output or interact with the database |
Return Requirement | Action functions should return nothing. | Filter functions must return their changes as output. |
Execution Scope | Actions can execute almost anything as long as the code is valid | Filters should work in an isolated manner so they don’t have any unintended side effects |
Common Functions | add_action() : Attaches a specified function to a hook within the do_action process. <br> remove_action() : Removes a function attached to a particular action hook. <br> do_action() : Executes the functions connected to the hook. <br> has_action() : Checks whether an action has been registered or not. | add_filter() : Attaches a function to a hook. <br> remove_filter() : Removes a function attached to a specified filter hook. <br> doing_filter() : Detects any filter currently being executed. <br> has_filter() : Checks if a filter has been registered. |
Example | By hooking into the do_action('wp_head') action, you can execute custom code whenever WordPress processes the site header. Example: add_action( 'wp_head', 'my_custom_function' ); | The apply_filters( 'admin_footer_text' , string $text ) filter can be hooked in to modify the text displayed in the admin footer. As of WordPress 5.4, its default value will show the sentence “Thank you for creating with WordPress.” in the admin area footer. Example: add_filter( 'admin_footer_text', 'my_footer_text_function' ); |
References | For a comprehensive list of actions: <br> Action Reference <br> Add Action | For a comprehensive list of filters: <br> Filter Reference <br> Add Filter |
Our WordPress Hooks List
1. Action Hook: wp_head
The wp_head action hook allows you to insert custom code into your WordPress site’s <head> section. This is particularly useful for adding meta tags, linking to external resources, or including analytics and tracking codes.
function add_custom_meta_tags() {
echo '<meta name="description" content="Custom description for SEO purposes">';
}
add_action('wp_head', 'add_custom_meta_tags');
Explanation:
- Function Definition: The add_custom_meta_tags function outputs a meta tag for SEO purposes. You can customize the content attribute to provide a unique description for your site.
- Hooking into wp_head: By attaching this function to the wp_head action using add_action(‘wp_head’, ‘add_custom_meta_tags’);, WordPress will execute this function and insert the meta tag into the <head> section of every page on your site. This allows you to dynamically add elements like meta descriptions, custom styles, or scripts.
2. Filter Hook: the_content
The the_content filter hook enables you to modify the content of posts or pages before it is displayed to users. This WordPress hook is commonly used for appending or prepending additional text, shortcodes, or HTML to the content.
function append_custom_text_to_content($content) {
if (is_single()) {
$content .= '<p>Thank you for reading!</p>';
}
return $content;
}
add_filter('the_content', 'append_custom_text_to_content');
Explanation:
- Function Definition: The append_custom_text_to_content function checks if the current view is a single post (is_single()). If true, it appends a thank-you message to the end of the post content.
- Hooking into the_content: By attaching this function to the the_content filter with add_filter(‘the_content’, ‘append_custom_text_to_content’);, WordPress will apply the function to post content before it is displayed. This allows you to dynamically modify post content for individual or all posts.
3. Action Hook: widgets_init
The widgets_init action hook is used to register custom widget areas (sidebars) or modify existing ones. This hook is essential for adding new areas where widgets can be placed, enhancing the flexibility of your theme’s layout.
function register_custom_sidebar() {
register_sidebar(array(
'name' => 'Custom Sidebar',
'id' => 'custom_sidebar',
'before_widget' => '<div class="custom-widget">',
'after_widget' => '</div>',
'before_title' => '<h2 class="custom-widget-title">',
'after_title' => '</h2>',
));
}
add_action('widgets_init', 'register_custom_sidebar');
Explanation:
- Function Definition: The register_custom_sidebar function uses register_sidebar to create a new widget area. The parameters specify the sidebar’s name, ID, and HTML structure for widgets and titles.
- name: The display name of the sidebar.
- id: A unique identifier for the sidebar, used in theme templates.
- before_widget and after_widget: HTML that wraps around each widget.
- before_title and after_title: HTML that wraps around the widget title.
- Hooking into widgets_init: By attaching this function to the widgets_init action with add_action(‘widgets_init’, ‘register_custom_sidebar’);, WordPress registers the new sidebar during the initialization of widgets, making it available for use in your theme.
4. Filter Hook: excerpt_more
The excerpt_more filter hook allows you to customize the “read more” text that appears at the end of post excerpts. By default, WordPress uses a standard string like “[…]” for the excerpt’s “read more” link. This filter gives you the flexibility to replace it with custom text or HTML.
function custom_excerpt_more($more) {
return '... <a href="' . get_permalink() . '">Read More</a>';
}
add_filter('excerpt_more', 'custom_excerpt_more');
Explanation:
- Function Definition: The custom_excerpt_more function takes the default more string as an argument and returns a custom string that includes a “Read More” link. This link directs users to the full post using get_permalink(), which dynamically retrieves the URL of the post.
- Hooking into excerpt_more: By using add_filter(‘excerpt_more’, ‘custom_excerpt_more’);, this function will replace the default excerpt end string with the custom text whenever WordPress generates post excerpts. This allows you to provide a more engaging or descriptive call-to-action.
5. Action Hook: admin_bar_menu
The admin_bar_menu action hook enables you to add custom items to the WordPress admin bar. The admin bar is the toolbar that appears at the top of the admin area and can also be seen by logged-in user logs on the front end. This hook is useful for adding shortcuts or custom links for easier access to admin functionalities.
function add_custom_admin_bar_item($wp_admin_bar) {
$wp_admin_bar->add_node(array(
'id' => 'custom_item',
'title' => 'Custom Item',
'href' => admin_url('admin.php?page=custom_page'),
));
}
add_action('admin_bar_menu', 'add_custom_admin_bar_item', 100);
Explanation:
- Function Definition: The add_custom_admin_bar_item function uses the $wp_admin_bar object to add a new item. The add_node method adds a new node to the admin bar with specific parameters:
- ‘id’: A unique identifier for the item.
- ‘title’: The text that will be displayed for the item.
- ‘href’: The URL that the item will link to, in this case, a custom admin page.
- Hooking into admin_bar_menu: By hooking this function with add_action(‘admin_bar_menu’, ‘add_custom_admin_bar_item’, 100);, the custom item is added to the admin bar with a priority of 100, ensuring it appears after the default items. This customization improves admin navigation and access to frequently used functions or pages.
6. Filter Hook: login_errors
The login_errors filter hook allows you to customize the error messages displayed on the WordPress dashboard login page. By default, WordPress provides generic error messages for login issues, such as incorrect usernames or passwords. This filter helps you provide more user-friendly or specific error messages.
function custom_login_errors($errors) {
if (isset($errors->errors['invalid_username'])) {
$errors->errors['invalid_username'] = array('Custom error message for invalid username.');
}
return $errors;
}
add_filter('login_errors', 'custom_login_errors');
Explanation:
- Function Definition: The custom_login_errors function checks if there is an error related to an invalid username. If so, it modifies the error message to a custom string in the WordPress login page. The $errors object contains error codes and messages, which are modified before being displayed on the login page.
- Hooking into login_errors: By using add_filter(‘login_errors’, ‘custom_login_errors’);, this function intercepts the login errors and applies the custom message. This enhances the user experience by providing clearer or more relevant feedback during the login process.
7. Action Hook: save_post
The save_post action hook is triggered when a post is saved or updated. This hook is essential for performing actions related to post data, such as saving or updating custom meta fields, modifying post content, or executing custom logic in the post editor.
function save_custom_post_meta($post_id) {
// Prevents auto-saving and post revisions from triggering this function
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($post_id)) return;
// Save custom field data
if (isset($_POST['custom_field'])) {
update_post_meta($post_id, 'custom_field', sanitize_text_field($_POST['custom_field']));
}
}
add_action('save_post', 'save_custom_post_meta');
Explanation:
- Function Definition: To avoid unnecessary processing, the save_custom_post_meta function first checks if the current save action is an auto-save or a post-revision. If the function proceeds, it checks for a custom field (custom_field) in the $_POST data. If present, it updates the post meta with the sanitized value.
- Hooking into save_post: By using add_action(‘save_post’, ‘save_custom_post_meta’);, this function executes whenever a post is saved or updated. This allows you to efficiently manage custom fields or other post-related data and ensure data integrity in the WordPress post editor.
8. Filter Hook: pre_get_posts
The pre_get_posts filter hook allows you to modify the main query before it retrieves posts from the database. This hook is particularly useful for customizing the query parameters, such as changing the number of posts displayed, adjusting sorting, or filtering posts based on specific criteria.
function modify_main_query($query) {
// Ensure this is the main query and not in the admin dashboard
if ($query->is_main_query() && !is_admin()) {
// Limit the number of posts displayed per page to 5
$query->set('posts_per_page', 5);
}
}
add_filter('pre_get_posts', 'modify_main_query');
Explanation:
- Function Definition: The modify_main_query function checks if the query being modified is the main query ($query->is_main_query()) and if it is not being executed in the admin area (!is_admin()). This ensures that only the front-end queries are affected. It then sets the posts_per_page parameter to 5, limiting the number of posts shown per page.
- Hooking into pre_get_posts: By adding this function to the pre_get_posts filter with add_filter(‘pre_get_posts’, ‘modify_main_query’);, WordPress applies this modification to the main query before fetching posts from the database. This allows you to customize the query globally for your site’s front end.
9. Action Hook: wp_enqueue_scripts
The wp_enqueue_scripts action hook is used to properly enqueue JavaScript and CSS files in WordPress. This hook ensures that scripts and styles are added in a way that avoids conflicts, maintains dependency order, and adheres to WordPress standards.
function enqueue_custom_scripts() {
// Enqueue a CSS stylesheet
wp_enqueue_style('custom-style', get_template_directory_uri() . '/css/custom-style.css');
// Enqueue a JavaScript file with jQuery as a dependency
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
Explanation:
- Function Definition: The enqueue_custom_scripts function enqueues a CSS stylesheet and a JavaScript file:
- wp_enqueue_style(‘custom-style’, get_template_directory_uri() . ‘/css/custom-style.css’); registers and enqueues a stylesheet located in the /css/ directory of the theme.
- wp_enqueue_script(‘custom-script’, get_template_directory_uri() . ‘/js/custom-script.js’, array(‘jquery’), null, true); registers and enqueues a JavaScript file located in the /js/ directory of the theme. This script depends on jQuery (array(‘jquery’)), does not specify a version (null), and is loaded in the footer (true).
- Hooking into wp_enqueue_scripts: By hooking this function with add_action(‘wp_enqueue_scripts’, ‘enqueue_custom_scripts’);, WordPress ensures that these scripts and styles are loaded at the appropriate time during the page rendering process. This prevents issues with script dependencies and maintains proper loading order.
10. Filter Hook: body_class
The body_class filter hook allows you to add custom classes to your WordPress site’s <body> tag. This is useful for applying specific CSS styles or targeting particular pages or post types with JavaScript.
function add_custom_body_class($classes) {
// Add a custom class to the body tag if viewing a single post
if (is_single()) {
$classes[] = 'single-post-class';
}
return $classes;
}
add_filter('body_class', 'add_custom_body_class');
Explanation:
- Function Definition: The add_custom_body_class function checks if the current view is a single post page using is_single(). If true, it adds ‘single-post-class’ to the array of body classes.
- Hooking into body_class: By applying this function with add_filter(‘body_class’, ‘add_custom_body_class’);, WordPress modifies the list of classes added to the <body> tag. This customization allows you to apply specific styles or JavaScript functionality to single post pages, enhancing your theme’s flexibility and responsiveness.
11. Action Hook: wp_enqueue_scripts
The wp_enqueue_scripts action hook is used to properly enqueue CSS stylesheets and JavaScript files on the front end of your WordPress site. Enqueuing scripts and styles ensures they are loaded in the correct order, prevent conflicts, and adhere to best practices for resource management.
function enqueue_custom_styles_and_scripts() {
// Enqueue a stylesheet
wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/css/custom-style.css');
// Enqueue a script
wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/js/custom-script.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_styles_and_scripts');
Explanation:
- Function Definition: The enqueue_custom_styles_and_scripts function is where you define which stylesheets and scripts to load:
- wp_enqueue_style(‘custom-style’, get_stylesheet_directory_uri() . ‘/css/custom-style.css’); registers and enqueues a CSS file located in the /css/ directory of your theme. The first parameter, ‘custom-style’, is a unique handle for the stylesheet.
- wp_enqueue_script(‘custom-script’, get_stylesheet_directory_uri() . ‘/js/custom-script.js’, array(‘jquery’), ‘1.0’, true); registers and enqueues a JavaScript file located in the /js/ directory of your theme. This script has ‘jquery’ as a dependency, meaning it will be loaded after jQuery, includes a version number ‘1.0’, and will be loaded in the footer (true).
- Hooking into wp_enqueue_scripts: By using add_action(‘wp_enqueue_scripts’, ‘enqueue_custom_styles_and_scripts’);, WordPress will execute this function during the appropriate phase of page rendering, ensuring your styles and scripts are included properly.
12. Filter Hook: the_author_meta
The the_author_meta filter hook allows you to modify the author meta information before it is displayed. This is useful for customizing how author information is presented on your site.
function modify_author_meta($author) {
return $author . ' - The Author';
}
add_filter('the_author_meta', 'modify_author_meta');
Explanation:
- Function Definition: The modify_author_meta function takes the current value of the author meta (e.g., the author’s name) and appends ‘ – The Author’ to it.
- Hooking into the_author_meta: By applying this function with add_filter(‘the_author_meta’, ‘modify_author_meta’);, WordPress will use the modified author meta value whenever it is displayed. This allows you to alter author information dynamically.
13. Action Hook: transition_post_status
The transition_post_status action hook is triggered when a post’s status changes. This hook is ideal for performing actions based on the transition between post statuses, such as logging changes, sending notifications, or updating related data.
function log_post_status_change($new_status, $old_status, $post) {
// Check if the status has actually changed
if ($old_status != $new_status) {
// Log the status change to the error log
error_log("Post ID {$post->ID} changed from {$old_status} to {$new_status}");
}
}
add_action(‘transition_post_status’, ‘log_post_status_change’, 10, 3);
Explanation:
- Function Definition: The log_post_status_change function receives three parameters:
- $new_status: The new status of the post.
- $old_status: The previous status of the post.
- $post: The post object that has changed. The function checks if the post’s status has changed and logs the change to the error log using error_log().
- Hooking into transition_post_status: By using add_action(‘transition_post_status’, ‘log_post_status_change’, 10, 3);, this function will be triggered whenever a post’s status changes, allowing you to handle such transitions effectively.
14. Filter Hook: widget_text
The widget_text filter hook allows you to modify the content of text widgets before they are rendered on the front end. This is useful for altering or enhancing the text displayed in widgets.
function modify_widget_text($text) {
// Replace 'old text' with 'new text' in widget content
return str_replace('old text', 'new text', $text);
}
add_filter('widget_text', 'modify_widget_text');
Explanation:
- Function Definition: The modify_widget_text function takes the text content of a widget as input and uses str_replace() to replace occurrences of ‘old text’ with ‘new text’.
- Hooking into widget_text: By adding this function with add_filter(‘widget_text’, ‘modify_widget_text’);, WordPress applies this modification to text widget content before it is displayed. This allows you to dynamically alter widget text across your site.
15. Action Hook: add_meta_boxes
The add_meta_boxes WordPress action hook allows you to add custom meta boxes to the post or page editor screens in WordPress. Meta boxes provide additional fields or interfaces that can be used to capture and display custom data related to posts or pages.
function add_custom_meta_box() {
add_meta_box(
'custom_meta_box_id', // Unique ID for the meta box
'Custom Meta Box Title', // Title of the meta box
'custom_meta_box_content', // Callback function to display the content of the meta box
'post', // Post type where the meta box should appear (e.g., 'post', 'page', or custom post types)
'side', // Context where the meta box should appear ('normal', 'side', or 'advanced')
'high' // Priority within the context ('high', 'core', 'default', 'low')
);
}
function custom_meta_box_content($post) {
// Retrieve existing value from post meta, if available
$value = get_post_meta($post->ID, 'custom_field', true);
// Display input field
echo '<input type="text" name="custom_field" value="' . esc_attr($value) . '" />';
}
add_action('add_meta_boxes', 'add_custom_meta_box');
Explanation:
- Function Definition:
- add_custom_meta_box uses add_meta_box() to create a new meta box. It specifies:
- ‘custom_meta_box_id’: A unique identifier for the meta box.
- ‘Custom Meta Box Title’: The title is displayed at the top of the meta box.
- ‘custom_meta_box_content’: The function that generates the HTML content for the meta box.
- ‘post’: Indicates that the meta box should appear on the post edit screen. You can change this to other post types or add multiple meta boxes for different post types.
- ‘side’: Positions the meta box in the editor’s sidebar.
- ‘high’: Sets the priority within the sidebar, affecting the order of meta boxes.
- add_custom_meta_box uses add_meta_box() to create a new meta box. It specifies:
- Content Callback:
- custom_meta_box_content retrieves the existing value of a custom field named ‘custom_field’ using get_post_meta(). It then displays an input field with the current value, allowing users to input or edit data related to the post.
- Hooking into add_meta_boxes:
- Using add_action(‘add_meta_boxes’, ‘add_custom_meta_box’);, WordPress will call add_custom_meta_box to register the meta box during the post editor initialization.
16. Filter Hook: login_headerurl
The login_headerurl filter hook allows you to change the URL to which the user login page header template file. By default, this link directs users to the WordPress.org website, but you can customize it to point to your site’s homepage or any other URL.
function custom_login_header_url() {
return home_url(); // Change to the home URL or any custom URL
}
add_filter('login_headerurl', 'custom_login_header_url');
Explanation:
- Function Definition:
- custom_login_header_url returns the URL you want the login header link to point to. In this example, home_url() returns the URL of your site’s homepage.
- Hooking into login_headerurl:
- By applying add_filter(‘login_headerurl’, ‘custom_login_header_url’);, WordPress uses the returned URL for the login page header link instead of the default URL, allowing for custom branding or redirection.
17. Action Hook: wp_insert_post
The wp_insert_post action hook is triggered after a post is inserted or updated in the database. This hook is useful for performing actions such as logging, sending notifications, or executing custom processing when a post is created or updated.
function on_post_insert($post_id, $post, $update) {
// Check if this is a new post (not an update)
if (!$update) {
// Log information about the newly inserted post
error_log("New post inserted with ID: {$post_id}");
}
}
add_action('wp_insert_post', 'on_post_insert', 10, 3);
Explanation:
- Function Definition:
- on_post_insert receives three parameters:
- $post_id: The ID of the post being inserted or updated.
- $post: The post object with details about the post.
- $update: A boolean indicating whether the post is being updated (true) or inserted (false).
- The function checks if $update is false, indicating a new post, and logs a message with the post ID to the error log using error_log().
- on_post_insert receives three parameters:
- Hooking into wp_insert_post:
- By using add_action(‘wp_insert_post’, ‘on_post_insert’, 10, 3);, this function will be called after a post is saved, enabling additional processing or logging.
18. Filter Hook: the_permalink
The the_permalink filter hook allows you to modify the permalink structure of posts or other content types. This can be useful for customizing URLs, adding query parameters, or changing permalink formats.
function modify_post_permalink($permalink, $post) {
// Check if the post type is 'post'
if ($post->post_type == 'post') {
// Replace 'category' with 'blog-category' in the permalink
$permalink = str_replace('category', 'blog-category', $permalink);
}
return $permalink;
}
add_filter('the_permalink', 'modify_post_permalink', 10, 2);
Explanation:
- Function Definition:
- modify_post_permalink takes two parameters:
- $permalink: The current permalink for the post.
- $post: The post object.
- The function checks if the post type is ‘post’ and modifies the permalink by replacing ‘category’ with ‘blog-category’ using str_replace().
- modify_post_permalink takes two parameters:
- Hooking into the_permalink:
- By using add_filter(‘the_permalink’, ‘modify_post_permalink’, 10, 2);, this function will alter the permalink structure whenever WordPress generates URLs for posts. This allows for custom URL formatting or enhancements.
19. Action Hook: comment_post
The comment_post action hook is triggered immediately after a comment is posted. It provides an opportunity to perform actions such as sending notifications, logging information, or executing additional processing based on the posted comment.
function on_comment_post($comment_ID, $approval) {
// Check if the comment was approved
if ($approval == 'approve') {
// Retrieve the comment object
$comment = get_comment($comment_ID);
// Send a notification email
wp_mail(
'[email protected]',
'New Comment Posted',
'A new comment was posted: ' . $comment->comment_content
);
}
}
add_action('comment_post', 'on_comment_post', 10, 2);
Explanation:
- Function Definition:
- on_comment_post takes two parameters:
- $comment_ID: The ID of the newly posted comment.
- $approval: The status of the comment (e.g., ‘approve’, ‘hold’).
- The function checks if $approval is ‘approve’. If true, it retrieves the comment details using get_comment() and sends an email using wp_mail() to notify about the new comment.
- on_comment_post takes two parameters:
- Hooking into comment_post:
- By using add_action(‘comment_post’, ‘on_comment_post’, 10, 2);, this function will be executed after a comment is posted, allowing you to perform additional actions such as sending notifications.
20. Filter Hook: comment_text
The comment_text filter hook allows you to modify the content of a comment before it is displayed on the WordPress site. This is useful for adding custom formatting, prefixes, or other modifications.
function custom_comment_text($comment_text) {
// Add a custom prefix to the comment text
return '<p>Custom Prefix: ' . $comment_text . '</p>';
}
add_filter('comment_text', 'custom_comment_text');
Explanation:
- Function Definition:
- custom_comment_text takes the original comment content as input and appends a custom prefix.
- The modified content is returned, which will be displayed instead of the original comment text.
- Hooking into comment_text:
- Using add_filter(‘comment_text’, ‘custom_comment_text’);, WordPress applies this filter to comment content before rendering it on the site, allowing for customization of how comments appear.
21. Action Hook: template_redirect
The template_redirect WordPress action hook is executed before loading the template file. It is often used for redirections or performing actions based on the current request.
function custom_redirect() {
if (is_page('old-page')) {
wp_redirect(home_url('/new-page'));
exit;
}
}
add_action('template_redirect', 'custom_redirect');
Explanation:
- Function Definition:
- custom_redirect checks if the current page is ‘old-page’ and, if true, redirects users to ‘new-page’ using wp_redirect().
- exit is used to terminate script execution immediately after the redirect to ensure no further code is run.
- Hooking into template_redirect:
- By using add_action(‘template_redirect’, ‘custom_redirect’);, this function will execute before WordPress loads the template, allowing for redirection based on conditions.
22. Filter Hook: excerpt_more
The excerpt_more WordPress filter hook allows you to customize the “read more” text that appears at the end of teh blog post excerpts. This can be useful for adding custom links or text in the login page footer.
function custom_excerpt_more($more) {
return '... <a href="' . get_permalink() . '">Continue Reading</a>';
}
add_filter('excerpt_more', 'custom_excerpt_more');
Explanation:
- Function Definition:
- custom_excerpt_more replaces the default excerpt ending with a custom “Continue Reading” link that directs users to the full post.
- Hooking into excerpt_more:
- Using add_filter(‘excerpt_more’, ‘custom_excerpt_more’);, WordPress will use this custom text for the excerpt’s “read more” link.
23. Action Hook: before_setup_theme
The before_setup_theme action hook is called before the theme setup process begins. It is used to initialize features or settings before the theme is fully loaded.
function custom_theme_setup() {
add_theme_support('post-thumbnails');
}
add_action('before_setup_theme', 'custom_theme_setup');
Explanation:
- Function Definition:
- custom_theme_setup adds support for post thumbnails by calling add_theme_support(‘post-thumbnails’). This feature allows the theme to use featured images for posts.
- Hooking into before_setup_theme:
- By using add_action(‘before_setup_theme’, ‘custom_theme_setup’);, this function will run before the theme setup is completed, ensuring the feature is available throughout the theme.
Learn about bootstrap WordPress themes here.
24. Filter Hook: the_post_thumbnail
The the_post_thumbnail WordPress filter hook allows you to modify the HTML output of post thumbnails. This can be useful for changing attributes or wrapping the image in additional HTML.
function custom_post_thumbnail_html($html) {
return str_replace('class="wp-post-image"', 'class="custom-thumbnail"', $html);
}
add_filter('the_post_thumbnail', 'custom_post_thumbnail_html');
Explanation:
- Function Definition:
- custom_post_thumbnail_html modifies the HTML for post thumbnails by changing the class attribute from ‘wp-post-image’ to ‘custom-thumbnail’.
- Hooking into the_post_thumbnail:
- Using add_filter(‘the_post_thumbnail’, ‘custom_post_thumbnail_html’);, this function will alter the HTML output of post thumbnails, allowing for custom styling or additional attributes.
25. Action Hook: init
The init action hook is called after WordPress has finished loading, but before any headers are sent. It is often used for initializing custom post types, taxonomies, or shortcodes.
function register_custom_post_type() {
register_post_type('custom_post',
array(
'labels' => array(
'name' => __('Custom Posts'),
'singular_name' => __('Custom Post'),
),
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'register_custom_post_type');
Explanation:
- Function Definition:
- register_custom_post_type registers a new custom post type called ‘custom_post’ with specified labels and settings.
- Hooking into init:
- Using add_action(‘init’, ‘register_custom_post_type’);, this function is called during the initialization phase, allowing for custom post type registration before WordPress handles other actions.
26. Filter Hook: widget_title
The widget_title filter hook allows you to modify the title of widgets before it is displayed. This can be useful for adding prefixes, suffixes, or changing widget titles dynamically.
function custom_widget_title($title) {
return 'Widget: ' . $title;
}
add_filter('widget_title', 'custom_widget_title');
Explanation:
- Function Definition:
- custom_widget_title adds the prefix ‘Widget: ‘ to every widget title.
- Hooking into widget_title:
- By using add_filter(‘widget_title’, ‘custom_widget_title’);, this function modifies widget titles before they are rendered.
27. Action Hook: admin_menu
The admin_menu WordPress action hook is used to add custom items to the WordPress admin menu. This can include adding new menu items, submenus, or custom admin pages.
function custom_admin_menu() {
add_menu_page(
'Custom Page Title', // Page title
'Custom Menu Title', // Menu title
'manage_options', // Capability required
'custom-page-slug', // Menu slug
'custom_admin_page_content' // Function to display page content
);
}
function custom_admin_page_content() {
echo '<h1>Welcome to the Custom Admin Page</h1>';
}
add_action('admin_menu', 'custom_admin_menu');
Explanation:
- Function Definition:
- custom_admin_menu adds a new top-level menu item in the WordPress admin with the title ‘Custom Menu Title’. It links to a page with the slug ‘custom-page-slug’ and displays content via custom_admin_page_content.
- Hooking into admin_menu:
- Using add_action(‘admin_menu’, ‘custom_admin_menu’);, this function adds custom admin menu items and pages.
28. Filter Hook: post_type_link
The post_type_link filter hook allows you to modify the permalink structure of custom blog post types. This is useful for customizing URLs of specific content types.
function custom_post_type_link($post_link, $post) {
if ($post->post_type === 'custom_post') {
return home_url('/custom/' . $post->post_name);
}
return $post_link;
}
add_filter('post_type_link', 'custom_post_type_link', 10, 2);
Explanation:
- Function Definition:
- custom_post_type_link changes the permalink structure for posts of type ‘custom_post’ to include a custom path (‘/custom/’).
- Hooking into post_type_link:
- By using add_filter(‘post_type_link’, ‘custom_post_type_link’, 10, 2);, this function alters the permalink URLs for custom post types.
29. Action Hook: wp_footer
The wp_footer action hook is used to add custom content or scripts to the footer of your site just before the closing </body> tag.
function custom_footer_content() {
echo '<p>Custom footer content goes here.</p>';
}
add_action('wp_footer', 'custom_footer_content');
Explanation:
- Function Definition:
- custom_footer_content outputs a paragraph with custom content in the footer of your site.
- Hooking into wp_footer:
- Using add_action(‘wp_footer’, ‘custom_footer_content’);, this function will add custom content just before the end of the <body> tag.
30. Filter Hook: widget_display_callback
The widget_display_callback filter hook allows you to modify the output of widgets before they are displayed. This is useful for altering widget HTML or applying custom styles.
function custom_widget_display($instance, $widget) {
$instance['title'] = 'Modified Title: ' . $instance['title'];
return $instance;
}
add_filter('widget_display_callback', 'custom_widget_display', 10, 2);
Explanation:
- Function Definition:
- custom_widget_display modifies the widget instance data, specifically changing the title by prefixing ‘Modified Title: ‘ to it.
- Hooking into widget_display_callback:
- By using add_filter(‘widget_display_callback’, ‘custom_widget_display’, 10, 2);, this function alters widget titles before the widget content is rendered.
Learn about top SEO plugins here.
The Art and Science of WordPress Hooks
Understanding and utilizing our WordPress Hooks list—Actions and Filters—is crucial for customizing and extending WordPress functionality. For more detailed information, refer to the WordPress Codex and WordPress Developer Resources.
By leveraging the resources on these, developers can customize WordPress to address specific needs and craft highly individualized sites. Nestify Hosting strategically complements this by delivering superior performance optimization, robust security, and developer-centric tools, along with expert support.
Get a head start on building your perfect site—sign up for a free trial with Nestify today and build your site on speedy hosting.
FAQs on the WordPress Hooks List:
Can I use hooks in custom plugins and themes?
Yes, hooks can be used in both custom plugins and themes. They are a core part of WordPress’s extensibility and allow you to modify or add functionality without changing the core files.
Can I pass parameters to hooks?
Yes, you can pass parameters to hooks. For filters, you can specify additional arguments when calling add_filter()
. For actions, you can define your function to accept parameters.
Why isn’t my hook working?
Ensure that:
- The function you’re hooking into exists and is properly named.
- The hook you’re using is correct and exists in WordPress or your theme/plugin.
- Your code is placed in the right location, such as the theme’s
functions.php
file or a custom plugin.