WordPress Actions & Filters
The WordPress Event-Driven Architecture (Hooks System)
WordPress core is designed around an Event-Driven Architecture. Instead of requiring developers to modify core WordPress files to add functionalityβwhich would be overwritten during WordPress updatesβWordPress core exposes thousands of execution checkpoints called Hooks.
When a web request is processed, WordPress executes sequentially from initialization to template rendering. As core reaches specific execution milestones, it checks if any plugin or theme has attached custom functions to those hooks.
The Hooks system is divided into two distinct categories:
- Actions (
add_action): Triggered when a specific event occurs in the WordPress lifecycle. Actions perform an operation (e.g., saving data, sending an email, enqueueing scripts, or echoing HTML) and return no value. - Filters (
add_filter): Triggered when WordPress is preparing data to be saved or displayed. Filters accept data as an argument, modify or transform that data, and must return the modified data back to WordPress.
ββββββββββββββββββββββββββββββββββββββββββββββββ
β WordPress Lifecycle Event β
ββββββββββββββββββββββββ¬ββββββββββββββββββββββββ
β
Is it modifying data or doing work?
β
βββββββββββββββββββββββββ΄ββββββββββββββββββββββββ
βΌ βΌ
βββββββββββββββββββββ βββββββββββββββββββββ
β ACTION HOOK β β FILTER HOOK β
β (Do Something) β β (Modify & Return) β
βββββββββββ¬ββββββββββ βββββββββββ¬ββββββββββ
β β
Calls callback function Passes value to callback
Executes task (echo, log, save) Transforms value
No return value required MUST return modified value
Actions vs. Filters: The Core Distinction
Actions (add_action / do_action):
- Purpose: To execute custom PHP logic at a specific point in execution.
- Execution Flow: Core fires
do_action('hook_name'). WordPress iterates through all functions attached viaadd_action('hook_name', 'callback')and runs them. - Return Value: None. Callback functions perform an action (such as echoing text to the screen, updating a database row, or sending HTTP headers) and end.
- Real-World Use Cases:
- Injecting analytics scripts into
<head>(wp_head). - Adding custom copyright text to the page footer (
wp_footer). - Processing form data when a post is published (
publish_post). - Enqueueing admin stylesheets (
admin_enqueue_scripts).
- Injecting analytics scripts into
Filters (add_filter / apply_filters):
- Purpose: To pass data through a pipeline of callbacks where each callback can inspect, modify, or replace the data before returning it.
- Execution Flow: Core passes data through
apply_filters('hook_name', $value). WordPress executes attached callbacks sequentially, passing the output of Callback 1 as the input to Callback 2. - Return Value: Mandatory. A filter callback MUST return the modified (or unmodified) data. Returning
nullor nothing wipes out the data entirely! - Real-World Use Cases:
- Appending an icon or badge to post titles (
the_title). - Injecting custom callout boxes or social share buttons into post bodies (
the_content). - Customizing excerpt word limits (
excerpt_length). - Modifying database query parameters before execution (
posts_where).
- Appending an icon or badge to post titles (
Hook Registration Parameters: Priority & Accepted Arguments
Both add_action() and add_filter() accept up to four parameters:
add_action( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 );
add_filter( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 );
1. Priority ($priority):
- Determines the order in which callback functions attached to the same hook are executed.
- Lower numbers = Earlier execution (e.g., priority
5runs before priority10). - Higher numbers = Later execution (e.g., priority
999runs after all standard functions). - Default Priority:
10. - Why it matters: If your plugin logic depends on another plugin or WordPress core feature initializing first (e.g., during the
inithook), you may need to assign a higher priority number (e.g.,20) so your callback runs after core setup is complete. Conversely, to override another plugin’s filter output, set a high priority number (e.g.,999).
2. Accepted Arguments ($accepted_args):
- Defines how many parameter variables WordPress should pass to your callback function.
- Default:
1. - Why it matters: Some WordPress hooks pass multiple contextual variables (e.g.,
save_postpasses$post_id,$post, and$update). If your callback expects 3 arguments, you MUST explicitly set$accepted_argsto3. If omitted, WordPress defaults to1and discards the remaining parameters.
2.4 WordPress Lifecycle & Conditional Tags
When writing hook callbacks, you often want your code to run only under specific conditionsβfor example, appending an emoji only to single blog post titles, or adding header meta tags only on singular pages.
WordPress provides Conditional Tags that return boolean (true/false) based on the current HTTP request context:
is_single(): Checks if a single blog post is being displayed.is_page(): Checks if a static WordPress page is being displayed.is_singular( $post_types ): Checks if a single post of any type (or specific post types like'post'or'product') is being displayed.is_admin(): Checks if the WP-Admin dashboard is currently active.is_front_page(): Checks if the site’s main front page is being displayed.
The Return Baseline Rule for Filters:
When using conditional checks inside a filter callback, you MUST return the original data if the condition evaluates to false:
Function Naming Conventions: the_* vs. get_the_*
WordPress core follows a strict naming convention for template functions:
the_*Functions (Display / Echo):- Examples:
the_title(),the_content(),the_excerpt(). - Behavior: Immediately outputs (echoes) the data directly to the HTTP response buffer.
- Usage: Used directly in theme template files (
single.php,header.php). Do NOT use inside filter callbacks or variable assignments.
- Examples:
get_the_*Functions (Data Retrieval / Return):- Examples:
get_the_title(),get_the_excerpt(),get_the_content(). - Behavior: Retrieves and returns the string value without printing it to the screen.
- Usage: Used inside PHP functions, variable declarations, strings, and hook callbacks (e.g., storing a post title into a variable to generate meta tags).
- Examples:
Deep-Dive Code Explanation
Lecture Code Snippets & Line-by-Line Breakdown
Snippet 1: Modular Inclusion of Hooks File
Explanation:
- Following the modular architecture from Lecture 05, all action and filter callbacks are organized inside
inc/hooks.php. require_onceuses the server path constantMSR_PLUGIN_DIR_PATHto safely includeinc/hooks.phpduring plugin bootup.
Snippet 2: Basic Action Hook β Injecting Footer Text
Line-by-Line Detailed Breakdown:
if ( ! defined( 'ABSPATH' ) ) exit;: Direct access security guard.function msr_footer_text() {: Declares a callback function namedmsr_footer_text.- `echo ‘<p…>: Outputs an HTML paragraph string directly to the browser output buffer.
add_action( 'wp_footer', 'msr_footer_text', 20 );: Registersmsr_footer_textonto thewp_footeraction hook with a priority of20(running after standard priority10theme footer callbacks).
Snippet 3: Basic Filter Hook β Conditional Emoji Prefix on Post Titles
Line-by-Line Detailed Breakdown:
function msr_post_title( $title ): Callback function accepting$title(the string returned by WordPress for the title).if ( is_singular( 'post' ) ): Checks whether the current request is displaying a single blog post.$emoji = 'π ';: Defines an emoji icon variable.return $emoji . $title;: Concatenates the emoji prefix with the original title and returns the modified string.return $title;: Essential fallback! If the page is NOT a single post (e.g., homepage, menu item, post list), returns the original$titleunaltered.add_filter( 'the_title', 'msr_post_title' );: Hooksmsr_post_titleinto WordPress’sthe_titlefilter pipeline.
Snippet 4: Filter Hook β Excerpt Word Length Modification
Line-by-Line Detailed Breakdown:
function msr_excerpt_length( $length ): Receives the integer word count$length.return 20;: Overrides the length, restricting automatically generated excerpts to 20 words.add_filter( 'excerpt_length', 'msr_excerpt_length', 999 );: Attaches the callback with priority999to ensure it overrides theme settings (e.g., Astra theme excerpt defaults).
Snippet 5: Filter Hook β Injecting Callout Heading into Content
Line-by-Line Detailed Breakdown:
msr_post_content( $content ): Accepts the full post HTML string$content.$heading = '<h2>...</h2>';: Defines custom HTML to inject.return $heading . $content;: Prepends the heading to$contentand returns the combined string.
Snippet 6: Advanced Action Hook β Injecting Open Graph Meta Tags into HTML <head>
Line-by-Line Detailed Breakdown:
add_action( 'wp_head', 'msr_header_meta_info', 20 );: Attaches callback towp_head, which fires inside the<head>...</head>section of the HTML document.if ( is_single() ): Restricts meta tag injection strictly to single post pages.$title = get_the_title();: Retrieves the current post title as a PHP variable without echoing it.$description = get_the_excerpt();: Retrieves the post excerpt as a variable.esc_attr( $title ): Sanitizes the title string to safely escape quotes and HTML characters before inserting it inside HTMLcontent="..."attributes.echo '<meta property="og:title"...: Prints the valid<meta>tag into the HTML document header.
3.2 Refactored Production-Ready Code (Namespaced & Escaped)
In commercial plugin development, placing functions in the global namespace risks function name collisions. Below is the refactored production-ready code using OOP/Namespaces and complete output escaping:
WordPress Technical Reference Guide
Table Essential WordPress Action Hooks Reference
| Action Hook Name | Trigger Point / Execution Lifecycle Stage | Common Plugin Use Cases |
|---|---|---|
plugins_loaded | Fires after all active plugins are fully loaded. | Instantiating plugin main classes, loading text domains. |
init | Fires after WP core finishes loading, before headers are sent. | Registering Custom Post Types (CPTs), taxonomies, dynamic blocks. |
admin_init | Fires when WP-Admin dashboard initializes. | Registering settings, fields, and options API sections. |
wp_head | Fires inside the HTML <head> tag on front-end pages. | Injecting Open Graph tags, SEO metadata, custom inline CSS/JS. |
wp_footer | Fires before the closing </body> tag on front-end pages. | Echoing copyright text, analytics scripts, modal markup. |
admin_footer | Fires before closing </body> tag in WP-Admin dashboard. | Injecting admin modal dialogs or custom footer scripts. |
save_post | Fires whenever a post/page is created, updated, or saved. | Saving custom meta box fields, triggering Webhooks. |
Table Essential WordPress Filter Hooks Reference
| Filter Hook Name | Passed Data Parameter | Expected Return Type | Common Plugin Use Cases |
|---|---|---|---|
the_title | $title (string) | string | Modifying, prefixing, or formatting post/page titles. |
the_content | $content (string) | string | Injecting ads, related posts, share buttons, or headings into posts. |
excerpt_length | $length (int) | int | Customizing maximum word count for automatic post excerpts. |
excerpt_more | $more (string) | string | Customizing “Read More” link/symbol appended to excerpts. |
the_excerpt | $excerpt (string) | string | Modifying formatted excerpt text output. |
body_class | $classes (array) | array | Adding custom CSS class names to the HTML <body> element. |
plugin_action_links | $actions (array) | array | Adding a “Settings” or “Docs” link to plugin list table in WP-Admin. |
Table WordPress Hooks API Core Functions
| Function Signature | Return Type | Purpose / Description |
|---|---|---|
add_action( $hook, $callback, $priority, $accepted_args ) | true | Attaches a custom callback function to an Action hook. |
add_filter( $hook, $callback, $priority, $accepted_args ) | true | Attaches a custom callback function to a Filter hook. |
do_action( $hook, ...$arg ) | void | Triggers custom Action hook, executing all attached callbacks. |
apply_filters( $hook, $value, ...$arg ) | mixed | Triggers custom Filter hook, passing $value through callbacks. |
remove_action( $hook, $callback, $priority ) | bool | Unhooks a previously attached action function. |
remove_filter( $hook, $callback, $priority ) | bool | Unhooks a previously attached filter function. |
has_action( $hook, $callback ) | `bool\ | int` |
Table Echo Display Functions vs. Return Data Functions
Echo Display Function (the_*) | Data Return Function (get_the_*) | Output Destination | Safe for Filter Callbacks? |
|---|---|---|---|
the_title() | get_the_title() | Echoes HTML vs. Returns String | β the_title() will break layout |
the_excerpt() | get_the_excerpt() | Echoes HTML vs. Returns String | β the_excerpt() will break layout |
the_content() | get_the_content() | Echoes HTML vs. Returns String | β the_content() will break layout |
the_post_thumbnail() | get_the_post_thumbnail() | Echoes <img> vs. Returns HTML string | β the_post_thumbnail() will break |
Table Essential WordPress Conditional Tags Reference
| Conditional Tag | Target Environment / Context | Returns true When: |
|---|---|---|
is_single() | Front-end | Displaying any single post (or specified post ID/slug). |
is_page() | Front-end | Displaying a static WordPress Page. |
is_singular( $types ) | Front-end | Displaying a single post of any specified type (e.g., 'post', 'product'). |
is_admin() | Back-end | Current page request is within WP-Admin dashboard. |
is_front_page() | Front-end | Displaying the site’s main front page. |
is_home() | Front-end | Displaying the blog post index page. |
is_archive() | Front-end | Displaying category, tag, author, or date archive pages. |
Practical Step-by-Step Plugin Implementation Guide
Follow these steps to implement and verify the Lecture 06 Actions & Filters code on your local site.
Step 1: Create the Hooks Module File
Inside your local plugin directory (wp-content/plugins/msr-plugin/inc/), create a file named hooks.php.
Step 2: Include hooks.php in the Bootstrapper
Ensure msr-plugin.php includes inc/hooks.php:
// Inside msr-plugin.php
require_once MSR_PLUGIN_DIR_PATH . 'inc/hooks.php';
Step 3: Populate inc/hooks.php
Paste the following functional implementation:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// 1. Footer Text Action
function msr_footer_custom_text() {
echo '<div style="background:#0073aa; color:#fff; text-align:center; padding:10px;">';
echo 'MSR Plugin Active: Actions & Filters Demonstrated Successfully!';
echo '</div>';
}
add_action( 'wp_footer', 'msr_footer_custom_text', 20 );
// 2. Post Title Emoji Filter
function msr_filter_post_title( $title ) {
if ( is_singular( 'post' ) && in_the_loop() ) {
return 'π ' . $title;
}
return $title;
}
add_filter( 'the_title', 'msr_filter_post_title' );
// 3. Excerpt Length Filter
function msr_custom_excerpt_length( $length ) {
return 15;
}
add_filter( 'excerpt_length', 'msr_custom_excerpt_length', 999 );
// 4. Post Content Overview Filter
function msr_filter_post_content( $content ) {
if ( is_singular( 'post' ) && is_main_query() ) {
$banner = '<div style="border-left:4px solid #0073aa; padding:8px; margin-bottom:15px; background:#f0f4f8;">';
$banner .= '<strong>Quick Overview:</strong> Thank you for reading this article on CSE Study247!';
$banner .= '</div>';
return $banner . $content;
}
return $content;
}
add_filter( 'the_content', 'msr_filter_post_content' );
// 5. Open Graph Meta Tags Action
function msr_inject_og_meta() {
if ( is_single() ) {
$title = get_the_title();
$desc = get_the_excerpt();
echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n";
echo '<meta property="og:description" content="' . esc_attr( $desc ) . '" />' . "\n";
}
}
add_action( 'wp_head', 'msr_inject_og_meta', 20 );
Step 4: Verification on Front-End & Classic Themes
- Activate Theme: Install and activate a classic blog theme like Astra.
- Verify Footer Action: Scroll to the bottom of any page; confirm the blue footer banner displays.
- Verify Title & Content Filter: Open a single blog post (e.g., Hello World). Confirm the π rocket emoji appears in the title, and the blue overview callout box appears above the post body.
- Verify Excerpt Filter: Open the blog index page (
is_home()); confirm excerpts are trimmed to 15 words. - Verify Open Graph Meta Injection: Right-click the single post page, select View Page Source, inspect
<head>, and locate<meta property="og:title"...tags.
Common Pitfalls, Security Vulnerabilities & Best Practices
1. Forgetting to Return Data in Filter Callbacks
- The Error: Writing
echo $data;or returning nothing in anadd_filter()callback function. - Symptom: Blank post titles, empty post content, or missing site layouts.
- Fix: Filters must ALWAYS end with
return $data;.
2. Omitting Fallback Returns Outside Conditional Blocks
- The Error:
function bad_title_filter( $title ) { if ( is_single() ) { return 'Prefix: ' . $title; } // Missing fallback return! } - Symptom: Post titles vanish on homepage, category archives, menus, and sidebars.
- Fix: Ensure
return $title;exists outside theifblock.
3. Using Echo Display Functions (the_*) Inside Filters
- The Error: Calling
the_title()inside awp_headorthe_contentcallback. - Symptom: Content gets printed out of order at the very top of the HTML payload rather than inside the intended element.
- Fix: Use retrieval functions like
get_the_title()orget_the_excerpt().
4. Infinite Recursion Loops in Hook Callbacks
- The Error: Calling
wp_update_post()inside asave_posthook without unhooking the callback first. - Symptom: Browser hangs, PHP timeout limit reached, server crashes (
PHP Fatal Error: Maximum function nesting level reached). - Fix: Remove the action before calling update functions, then re-hook it:
remove_action( 'save_post', 'my_save_callback' ); wp_update_post( $my_data ); add_action( 'save_post', 'my_save_callback' );
5. Unescaped Output in Meta Tags (XSS Vulnerability)
- The Error: Printing raw strings inside HTML attributes:
echo '<meta content="' . $title . '">'; - Symptom: If a post title contains double quotes (
"Hello "World"), the attribute breaks and attackers can inject malicious JavaScript (" ><script>...). - Fix: Always wrap attribute strings in
esc_attr()and HTML strings inesc_html().
7. Cumulative Technical Interview Preparation (25 Questions)
Basic Questions (Q1 – Q5)
Q1: What is the fundamental difference between an Action hook and a Filter hook in WordPress?
- Answer: An Action hook (
add_action) allows you to execute custom PHP logic at a specific lifecycle event without returning a value. A Filter hook (add_filter) passes data to your callback function, allowing you to modify and must return the modified data back to WordPress. - Follow-Up Question: What happens if you forget to return data in a filter callback?
- Answer: WordPress receives
nullor nothing, completely wiping out that data from being displayed or processed.
- Answer: WordPress receives
Q2: What are the default priority and accepted arguments values in add_action()?
- Answer: Default priority is
10, and default accepted arguments count is1. - Follow-Up Question: How do you make a callback execute after all standard priority 10 callbacks have finished?
- Answer: Assign a higher priority number, such as
20or999.
- Answer: Assign a higher priority number, such as
Q3: Which WordPress action hook is used to inject custom HTML <meta> tags into the document head?
- Answer:
wp_head. - Follow-Up Question: Which hook is used to inject scripts right before
</body>?- Answer:
wp_footer.
- Answer:
Q4: Why should you use get_the_title() instead of the_title() inside an action or filter callback?
- Answer:
the_title()immediately echoes the title directly to the browser output buffer, breaking HTML layout order.get_the_title()returns the title as a PHP string variable for processing. - Follow-Up Question: What parameter can you pass to
get_the_title()?- Answer: A post ID or post object (defaults to the current post in the loop).
Q5: What does the conditional tag is_singular() do?
- Answer: It checks if a single post, page, or custom post type item is currently being viewed.
- Follow-Up Question: How does
is_singular('product')differ fromis_single()?- Answer:
is_singular('product')specifically checks for the ‘product’ custom post type, whereasis_single()checks for standard blog posts.
- Answer:
Intermediate Questions (Q6 – Q10)
Q6: Explain how custom hooks are created in WordPress core or third-party plugins.
- Answer: Custom actions are created using
do_action('custom_action_name', $arg1, $arg2). Custom filters are created using$value = apply_filters('custom_filter_name', $value, $arg1). Third-party developers can then attach callbacks to these hooks usingadd_actionoradd_filter. - Follow-Up Question: Why do plugin authors create custom hooks inside their plugins?
- Answer: To make their plugins extensible, allowing other developers to add add-ons or modify plugin behavior without editing source code.
Q7: How does the $accepted_args parameter prevent PHP warnings in multi-argument hooks?
- Answer: If a hook passes 3 variables (e.g.,
save_postpasses$post_id,$post,$update), setting$accepted_args = 3instructs WordPress to pass all 3 arguments to the callback. If left at default1, passing 3 parameters in the function definition causes PHP missing argument warnings or uninitialized variable errors. - Follow-Up Question: Write the syntax to hook a function expecting 2 arguments to
save_postwith priority 15.- Answer:
add_action( 'save_post', 'my_callback', 15, 2 );
- Answer:
Q8: What is the difference between remove_action() and remove_all_actions()?
- Answer:
remove_action()unhooks a specific callback function from a hook at a specified priority.remove_all_actions()unhooks every callback attached to that hook regardless of priority. - Follow-Up Question: Why must the
$priorityparameter inremove_action()match the exact priority passed inadd_action()?- Answer: WordPress indexes hook callbacks by priority; passing a mismatched priority causes
remove_action()to fail quietly.
- Answer: WordPress indexes hook callbacks by priority; passing a mismatched priority causes
Q9: How can you check if an action or filter has already been registered?
- Answer: Use
has_action( $hook_name, $callback )orhas_filter( $hook_name, $callback ). They return the priority integer if attached, orfalseif not attached. - Follow-Up Question: What does
did_action( $hook_name )return?- Answer: The number of times an action hook has fired during the current request lifecycle.
Q10: How do you prevent infinite loops when saving post meta inside a save_post callback?
- Answer: Check for autosaves (
DOING_AUTOSAVE), verify nonces, check user capabilities, and temporarily callremove_action('save_post', 'my_callback')before triggeringwp_update_post(), then re-hook it afterward.
Advanced Questions (Q11 – Q15)
Q11: How does WordPress manage the execution chain when multiple plugins hook into apply_filters()?
- Answer: WordPress executes filter callbacks sequentially ordered by priority. The value returned by Callback 1 is passed as the input argument to Callback 2, creating a sequential data modification pipeline.
- Follow-Up Question: What happens if Callback 1 returns
falseor an empty array?- Answer: Callback 2 receives
falseor an empty array as its input, which may break Callback 2 if it expects a specific data type like a string or object.
- Answer: Callback 2 receives
Q12: How do you hook an Object-Oriented class method to an Action or Filter?
- Answer: Pass an array containing the object instance and method name string:
add_action( 'init', array( $this, 'my_method' ) );or for static class methods:add_action( 'init', array( 'My_Class', 'my_static_method' ) );. - Follow-Up Question: How do you unhook an anonymous (closure) function?
- Answer: Closures cannot be unhooked easily via standard
remove_action()because they lack a named reference. You must iterate through the global$wp_filterarray object to find and remove them.
- Answer: Closures cannot be unhooked easily via standard
Q13: What security function must be applied when echoing user-controlled titles inside HTML attributes in wp_head?
- Answer:
esc_attr(). - Follow-Up Question: What function should be used for escaping URLs inside
hreforsrcattributes?- Answer:
esc_url().
- Answer:
Q14: Explain the difference between is_single(), is_page(), and is_singular().
- Answer:
is_single()returns true for single blog posts or custom post types (excluding pages/attachments).is_page()returns true for static Pages.is_singular()returns true for any single item (posts, pages, attachments, or custom post types). - Follow-Up Question: What does
is_singular( array( 'post', 'product' ) )evaluate?- Answer: Returns true if the request is viewing a single standard post OR a single WooCommerce product.
Q15: How does in_the_loop() enhance conditional logic inside the_title filter callbacks?
- Answer:
the_titleis fired for main content posts as well as navigation menus, sidebar widgets, and footer links. Checkingin_the_loop()ensures your title modification applies only to main post content titles inside the main query loop, avoiding corrupting menu item titles.
Coding Questions (Q16 – Q20)
Q16: Write a callback function hooked to the_content that appends a custom text signature to single post pages.
function msr_append_signature( $content ) {
if ( is_singular( 'post' ) && in_the_loop() ) {
$sig = '<p class="msr-signature">Written by CSE Study247 Team</p>';
return $content . $sig;
}
return $content;
}
add_filter( 'the_content', 'msr_append_signature' );
Q17: Write an action callback hooked to wp_head with priority 5 that prints a Google Fonts link tag.
function msr_enqueue_google_fonts() {
echo '<link rel="preconnect" href="https://fonts.googleapis.com">' . "\n";
echo '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto&display=swap">' . "\n";
}
add_action( 'wp_head', 'msr_enqueue_google_fonts', 5 );
Q18: Correct the severe bug in this filter code:
Buggy Code:
add_filter( 'the_title', function( $title ) {
if ( is_single() ) {
echo '<h1>' . $title . '</h1>';
}
} );
Corrected Code:
add_filter( 'the_title', function( $title ) {
if ( is_single() && in_the_loop() ) {
return '<h1>' . esc_html( $title ) . '</h1>';
}
return $title;
} );
Explanation: The buggy code used echo instead of return, omitted the fallback return $title, and lacked output escaping.
Q19: Write a callback function attached to excerpt_length that sets excerpt length to 30 words with priority 20.
function msr_custom_30_word_excerpt( $length ) {
return 30;
}
add_filter( 'excerpt_length', 'msr_custom_30_word_excerpt', 20 );
Q20: Write an OOP class constructor that hooks a method load_scripts to wp_enqueue_scripts.
class MSR_Asset_Loader {
public function __construct() {
add_action( 'wp_enqueue_scripts', array( $this, 'load_scripts' ) );
}
public function load_scripts() {
wp_enqueue_style( 'msr-main-style', MSR_PLUGIN_DIR_URL . 'public/css/main.css' );
}
}
new MSR_Asset_Loader();
Scenario-Based Questions (Q21 – Q25)
Q21: A developer filters the_title to add an icon, but suddenly navigation menu items on the header also display the icon. How do you resolve this?
- Answer: Add
in_the_loop() && is_main_query()to the conditional check inside the callback so the title filter applies only to posts inside the main content loop, leaving menu items untouched.
Q22: You modify excerpt_length to return 15 words, but your client’s theme still displays 55 words. What is happening and how do you fix it?
- Answer: The theme or another plugin is also filtering
excerpt_lengthwith a higher priority (e.g., priority100). Increase your filter priority to999(add_filter('excerpt_length', 'my_func', 999)) to ensure your filter runs last.
Q23: Your plugin adds a callback to wp_head to output meta tags, but nothing appears in the source code. What is the first thing you check in the theme?
- Answer: Check if the theme’s
header.phpfile containswp_head();right before</head>. Ifwp_head();is missing from the theme, no action callbacks attached towp_headwill fire.
Q24: You are building a security plugin that needs to log every time a user logs in. What hook do you use?
- Answer: Use the
wp_loginaction hook (add_action( 'wp_login', 'my_login_logger', 10, 2 );), which receives$user_loginand$userobject.
Q25: A client wants to automatically append a “Related Posts” shortcode output to the bottom of every blog post. Do you use an Action or a Filter?
- Answer: Use a Filter on
the_content. Checkif ( is_singular('post') && in_the_loop() ), executedo_shortcode('[related_posts]'), append it to$content, and return$content.
8. Interactive Practice & Skill Assessment
Q1: Which statement correctly describes a WordPress Action hook?
- A) It must return modified data.
- B) It executes custom code at a specific event and returns no value.
- C) It runs only in the WP-Admin dashboard.
- D) It overwrites WordPress core functions.
- Answer: B
- Explanation: Action hooks execute operations and return no value.
Q2: What is the mandatory rule for all filter callback functions?
- A) They must use
echoto output HTML. - B) They must terminate with
exit;. - C) They must return the data value (modified or original).
- D) They must take at least 3 parameters.
- Answer: C
- Explanation: Filters must return data; failing to return data results in data erasure.
Q3: Which function is used to fire a custom Action hook in your own plugin?
- A)
apply_filters() - B)
do_action() - C)
add_action() - D)
run_action() - Answer: B
- Explanation:
do_action()executes callbacks attached to a custom action hook.
Q4: If two callbacks are attached to the same hookβone with priority 5 and one with priority 15βwhich runs first?
- A) Priority 15
- B) Priority 5
- C) They run simultaneously in parallel.
- D) Priority order is randomized.
- Answer: B
- Explanation: Lower priority numbers execute earlier.
Q5: What function returns the post title without echoing it to the browser?
- A)
the_title() - B)
echo_title() - C)
get_the_title() - D)
print_title() - Answer: C
- Explanation:
get_the_title()returns the title as a string variable.
Q6: Which hook executes inside the <head> section of WordPress front-end pages?
- A)
wp_footer - B)
wp_head - C)
admin_head - D)
init - Answer: B
- Explanation:
wp_headfires inside the<head>element on front-end requests.
Q7: What conditional tag checks if a single blog post is being displayed?
- A)
is_admin() - B)
is_home() - C)
is_single() - D)
is_archive() - Answer: C
- Explanation:
is_single()returns true for single blog posts.
Q8: What security function should wrap string attributes when echoing HTML inside wp_head?
- A)
esc_attr() - B)
esc_sql() - C)
sanitize_text_field() - D)
wp_strip_all_tags() - Answer: A
- Explanation:
esc_attr()escapes strings for safe use inside HTML attributes.
Q9: What parameter in add_filter() controls the number of arguments passed to the callback?
- A)
$priority - B)
$accepted_args - C)
$version - D)
$handle - Answer: B
- Explanation:
$accepted_argsspecifies the number of arguments passed to the callback.
Q10: True or False: Filter callbacks can be attached to action hooks without causing errors.
- A) True
- B) False
- Answer: B
- Explanation: Action callbacks don’t require return values, while filters require return values. Mixing them leads to logical errors and missing data.
8.2 Hands-On Coding Exercises
Exercise 1: Custom Action Hook Declaration
Write code in a main file to trigger a custom action hook named msr_after_content_render passing $post_id.
// Solution
$post_id = get_the_ID();
do_action( 'msr_after_content_render', $post_id );
Exercise 2: Attaching Callback to Custom Action
Write an action callback hooked to msr_after_content_render accepting $post_id and echoing a container div.
// Solution
function msr_render_after_content_box( $post_id ) {
echo '<div class="msr-custom-box">Post ID: ' . esc_html( $post_id ) . '</div>';
}
add_action( 'msr_after_content_render', 'msr_render_after_content_box', 10, 1 );
Exercise 3: Modern Anonymous Filter Function
Write a filter on excerpt_more using an anonymous function (closure) returning '... [Read Full Story]'.
// Solution
add_filter( 'excerpt_more', function( $more ) {
return '... <a href="' . esc_url( get_permalink() ) . '">[Read Full Story]</a>';
} );
Exercise 4: Conditional Class Insertion via Filter
Write a callback hooked to body_class filter that adds 'msr-single-active' class array entry on single posts.
// Solution
function msr_add_body_class( $classes ) {
if ( is_single() ) {
$classes[] = 'msr-single-active';
}
return $classes;
}
add_filter( 'body_class', 'msr_add_body_class' );
Exercise 5: Debugging Missing Filter Return
Fix the broken code:
// BROKEN CODE
add_filter( 'the_title', function( $title ) {
if ( is_page() ) {
return 'Page: ' . $title;
}
} );
// CORRECTED CODE
add_filter( 'the_title', function( $title ) {
if ( is_page() ) {
return 'Page: ' . esc_html( $title );
}
return $title; // Added missing fallback return
} );
9. Quick Revision & Cheatsheet
5-Minute Core Takeaways
- Hooks Architecture: WordPress relies on Hooks (
ActionsandFilters) for event-driven extensibility without editing core files. - Actions (
add_action): Perform tasks, echo HTML, save data, return NO value. - Filters (
add_filter): Modify data parameters, MUST ALWAYS return the modified or original value. - Priority Control: Default is
10. Lower numbers execute earlier; higher numbers execute later. - Data Escaping: Always wrap attribute strings in
esc_attr()and HTML strings inesc_html()inside action/filter callbacks.