Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between add_filter versus add_action

I was looking over my functions.php and wondering why CODE A uses add_action while CODE B uses add_filter ?
The main goal of CODE A is to both include and exclude specific categories.
The main goal of CODE B is to exclude specific categories.

Is it correct to use add_action for CODE A
and add_filter for CODE B?



CODE A: Display specific category (called "featured") for homepage, instead of "the most recent posts"

function featured_category( $query ) {

    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'category_name', 'featured' );
        $query->set( 'category__not_in', array(60, 61) );
        $query->set( 'posts_per_page', 5 );
    }
}
add_action( 'pre_get_posts', 'featured_category' );



CODE B: Exclude "sponsored posts categories" for search results

function search_filter($query) {

    if ( $query->is_search && $query->is_main_query() ) {
        $query->set('post_type', 'post');
        $query->set( 'category__not_in', array(60, 61) );
        $query->set( 'posts_per_page', 20 );
    }

    return $query;
}
add_filter('pre_get_posts', 'search_filter');
like image 717
stadisco Avatar asked Oct 20 '14 03:10

stadisco


People also ask

What is Do_action and Add_action?

do_action creates an action hook, add_action executes hooked functions when that hook is called.

What is use of Add_action in WordPress?

The add_action function is arguably the most used function in WordPress. Simply put, it allows you to run a function when a particular hook occurs.

What is use of Add_filter in WordPress?

WordPress offers filter hooks to allow plugins to modify various types of internal data at runtime. A plugin can modify data by binding a callback to a filter hook. When the filter is later applied, each bound callback is run in order of priority, and given the opportunity to modify a value by returning a new value.

What is the difference between action hook and filter in WordPress?

Whereas Filters Hook still needs data. Actions can have any functionality, and Filters can exist to modify data. Actions may or may not passed any data by their action hook, and Filters are passed data to modify by their hook. Actions do not return their changes, and Filters must return their changes.


1 Answers

pre_get_posts is an action and not a filter. $query is passed by reference which is why CODE A works without returning anything.

CODE B returns $query but again that code works because query has been passed by reference. The return value of the hook isn't assigned to anything.

do_action_ref_array( 'pre_get_posts', array( &$this ) ); 

add_action and add_filter are used in different contexts but the code is the same (add_action is an alias of add_filter). While both sets of code posted will work the correct usage is add_action.

like image 76
Nathan Dawson Avatar answered Sep 20 '22 15:09

Nathan Dawson