Support » Plugins » Filters vs Actions -from a newbe

  • Hi
    I’m having difficulty understanding the difference between Action and Filter functions.

    to quote from codex:

    Actions are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying a page of the admin panel. Your plugin can respond to the event by executing a PHP function, which might do one or more of the following:

    * Modify database data
    * Send an email message
    * Modify what is displayed in the browser screen (admin or end-user)

    Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages), and between the browser and the database (when WordPress is adding new posts and comments to the database);

    So, are filters a subset of actions?
    it seems I could use an action to change the text of the post for instance, instead of a filter?
    what would be a good example of correctly using filters while actions would be inappropriate for the situation?
    when should I use an action and when a filter?

    do the ‘hooks’ for actions and filters overlap? -can I add a either a filter or an action to the same hook?

    Thanks in advance for any answers and I apologize if this has been answered to death before but I could not find a forum post on this exactly..

    Thanks!

    Betsy

Viewing 9 replies - 1 through 9 (of 9 total)
  • Hi Betsy, I hope this explains everything!

    So, are filters a subset of actions?

    They are basically the same function applied to different contexts.

    If you take a peek into the core, you will see that add_action is actually a wrapper function for add_filter:

    function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
        return add_filter($tag, $function_to_add, $priority, $accepted_args);
    }

    it seems I could use an action to change the text of the post for instance, instead of a filter?

    Actually, you would use a filter for this situation. Let’s pretend that WordPress is a Mexican restaurant and we have ordered a taco as illustrated by the following code…

    <?php $taco = 'chicken'; ?>

    Basically, we have no choice… we will always be served a chicken taco. However, the same expression could be stated using the apply_filters() function. It is like ordering a taco and having the server ask you “well what kind of taco would you like?”

    <?php
    $taco = apply_filters( 'get_taco', 'chicken' );
    ?>

    The above code gives us access to the type of taco that we would like to have served. We can create a function which hooks into WordPress an changes the default value of $taco.

    <?php
    add_filter( 'get_taco', 'my_special_order' );
    function my_special_order( $content ) {
        return 'shredded beef';
    }
    ?>

    By adding the above code to you theme’s functions.php file or to a custom plugin, you are able to change the value of the variable $taco to whatever you like. Notice that the function “my_special_order” accepts one value. In this situation the value of $content is equal to the value of the second argument passed to the apply_filters() function. In this example it would be “chicken”.

    <?php
    add_filter( 'get_taco', 'my_special_order' );
    function my_special_order( $content ) {
        return $content . ' and avocado';
    }
    ?>

    The above code appends a string to the end of “chicken” resulting in a value of “chicken and avocado”.

    what would be a good example of correctly using filters while actions would be inappropriate for the situation?

    Basically, there usually is no choice for a plugin or theme developer as to which method they can use. The WordPress core is filled with calls to apply_filters() and do_action(). If I need to change the value of a piece of data, I will search through the core until I locate the file where that data is defined and see if it is possible to filter it’s value.

    If I need to do something at a certain time, I will look for calls to the do_action() hook. A simple example would be if I wanted to print custom css to the head of the document. I could easily add the following code to my theme’s functions.php file:

    <?php
    add_action( 'wp_head', 'print_my_custom_scripts' );
    function print_my_custom_scripts(){
        print '<style type="text/css">.red{color:#f00;}</style>';
    }
    ?>

    Notice how this time, the function did not return a value – it did something -> it printed text to the browser.

    Filters change data while actions allow us to do stuff.

    when should I use an action and when a filter?

    You would want to use an action where you need to do something at a certain point in time… add options to the database or print css or javascript.

    You should use a filter where you would want to alter the value of some data that WordPress has passed through the apply_filters() function.

    do the ‘hooks’ for actions and filters overlap? -can I add a either a filter or an action to the same hook?

    Actually, both filters and actions are hooks. That being said, the answer is “no”.

    Thread Starter betsyv

    (@betsyv)

    Thanks for the detailed answers!
    I’m beginning to grasp the concepts

    If I may, I have one more question..

    You explained:

    If I need to do something at a certain time, I will look for calls to the do_action() hook. A simple example would be if I wanted to print custom css to the head of the document.

    Isn’t printing to the user client ‘Filtering’?

    Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages) [again from codex above..]

    How is the context of printing custom css (Action function) different from the context of a Filter function?

    Thanks for your time and effort!

    Extremely appreciated 🙂
    Betsy

    Thanks for the detailed answers!
    I’m beginning to grasp the concepts

    No problem, glad I could be of some help.

    Isn’t printing to the user client ‘Filtering’?

    Although this article at Wikipedia does not cite any sources, it has have this to say in regards to what a filter is:

    In chemistry and common usage, a filter is a device (usually a membrane or layer) that is designed to physically block certain objects or substances while letting others through.

    Basically, this implies that there is a something that exists which may contain objects or substances that are non-desirable for a certain purpose. In WordPress filters are used where something exists and we desire to change that something. Something is usually a piece of data… either a hard-coded variable in WordPress core or user supplied data that has been stored in the database. The key thing to remember is that filters almost always affect a piece of information. When you see plugin or theme code that uses add_filter() it is almost always applied to a function that returns a value and does not print, execute a query or anything like that.

    On the other hand actions are used mainly throughout the core to allow developers to add their own custom code at certain places in time. Take a look at the WordPress Action Reference where you will find a list of actions which are in place during a typical request. If a developer desires to print `<p>”HEY YOU GUYS!”</p>’ at the top of the sidebar, they can use the action hook ‘get_sidebar’ and add their function to the list of functions which fire at that given point in time.

    How is the context of printing custom css (Action function) different from the context of a Filter function?

    It is very important that you be able to recognize that in the filters example we changed data that already existed and in the actions example we printed data at a given point in time.

    Maybe this might help out. It’s a quick example of filtering that uses an array:

    function media_upload_tabs() {
    	$_default_tabs = array(
    		'type' => __('From Computer'), // handler action suffix => tab text
    		'type_url' => __('From URL'),
    		'gallery' => __('Gallery'),
    		'library' => __('Media Library')
    	);
    	return apply_filters('media_upload_tabs', $_default_tabs);
    }

    The above code was taken from line 16 of /wp-admin/includes/media.php and is the definition of a function whose sole purpose is to return an array. Notice that the apply_filters() function has been used in the return statement to allow developers to hook into and filter the value of the array. A developer could add or delete a key/value pair from the array if they were so inclined. They could make the function return false which would most likely disable navigation on the uploads screen… Basically freedom is given to alter the value of a certain piece of data.

    With simple action hooks, there is no data to alter therefore you are not changing anything you are using php to do something btw – sorry that I don’t have another way to say this other than ‘do something’ – I know it’s very vague 🙂

    Actually, in php there are a few elementary functions that do something: print -> outputs data to the screen, exit -> terminates execution of the script all together.

    These function do not alter data or return a value, they just do something -> which it what actions do as well.

    Thread Starter betsyv

    (@betsyv)

    mfields,
    Thanks for the clear reply!
    I think I got it, now I’ll try diving into
    my first attempt at plugin development 🙂
    Thanks for your time and patience!
    Betsy

    Val

    (@vlbooth)

    mfields, thank you for this explanation. betsyv, thank you for asking!

    Checking my understanding with this…
    If I see return apply_filters( , ,) in a function, this is a hook indicating I can change what that function does. Essentially it’s an indicator of “filterability,” yes?

    mfields, I really appreciate your detailed explanation as well. In order for me to play around with the Thematic framework, I too wanted to understand the difference between actions and filters, and your examples really helped me decide on what I should be using. Thanks again.

    vlbooth + webgrrrl,
    Thanks! I had alot of fun writing this. Glad I could help you understand the ins and outs of actions and filters – they are by far my favorite feature in WordPress.

    Good work on this explanation mfields. Much appreciated!

    Thanks Mfields. Good read. 🙂 More wiser, but we’ll see how it goes in practise. *Getting back to tinkering*

Viewing 9 replies - 1 through 9 (of 9 total)
  • The topic ‘Filters vs Actions -from a newbe’ is closed to new replies.