differnce between add_filter() and add_action()

1. Purpose

  • add_action() → Used to execute custom code at specific points (hooks) during WordPress execution.
  • add_filter() → Used to modify existing data before it is used or displayed.

2. Syntax

add_action( $hook, $function_to_add, $priority, $accepted_args );
add_filter( $hook, $function_to_add, $priority, $accepted_args );

They look almost the same. The main difference is what your function does.


3. Example of add_action()

Add a message before the post content:

function mytheme_before_content() {
    echo '<p class="notice">Welcome to my blog!</p>';
}
add_action( 'the_content', 'mytheme_before_content' ); // action

✅ Runs code at the hook, doesn’t return modified content.


4. Example of add_filter()

Change the length of excerpts:

function mytheme_custom_excerpt_length( $length ) {
    return 20; // modifies the value
}
add_filter( 'excerpt_length', 'mytheme_custom_excerpt_length' ); // filter

✅ Modifies a value and returns it back to WordPress.


5. Key Rule

  • Actions → Do something. (output HTML, enqueue scripts, save data, etc.)
  • Filters → Change something. (modify titles, text, content, classes, etc.)

6. Comparison Table

Featureadd_action()add_filter()
PurposeRun code at a specific hookModify and return data
Return valueNothing requiredMust return a value
Example usageEnqueue styles, add meta box, display HTMLModify excerpt length, change title, filter content
Hook typeAction hookFilter hook

In short:

  • Use add_action() when you want to add functionality.
  • Use add_filter() when you want to change/modify data.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *