What Is The Difference Between Actions And Filters In WordPress

In this article, we are going to learn what is The difference between actions and filters
WordPress hooks are pre-defined points in the WordPress core code that developers can use to inject additional code or modify a variable. WordPress hooks have two types of hooks, Actions, and Filters.

WordPress Actions:

WordPress actions are benchmarks where the developer needs to execute a specific code at a specific event.

if a developer wants to make WordPress publish the post to social networks at the same moment the administrator publishes the post. He only needs to add the publishing code to save_post.

Example:

<?php
add_action(“save_post”, “publish_to_facebook”); function publish_to_facebook( $post_id )
{
// You can add any code here and it will be executed when the user saves a post.
}

WordPress Filters:

WordPress filters have the same idea as actions, but the main difference is that filters are used to modify variables. Unlike actions, filter code must return a value, which is the modified copy of the original value. For example, when WordPress displays the title of each post. We might need to modify the title by capitalizing it or any other modifications we want.

The filter which we should use in this case is  the_title. You can find a list of the pre-defined filter hooks in the WordPress codex. All relevant links are listed below.

Example:

<?php
add_filter(‘the_title’ , ‘capitalize_post_titles’);
function capitalize_post_titles( $post_title )
{
     $title = ucwords( $post_title );
    return $title;
}

The filter is return value while the action does not return value it just processes when some specific event.

Submit a Comment

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

Subscribe

Select Categories