7

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');
benny-ben
  • 422
  • 5
  • 15
stadisco
  • 557
  • 2
  • 7
  • 22

1 Answers1

2

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.

Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58
  • Thanks, I will use `add_action` . But just curious, in terms of website speed, which will load a website faster, `add_action` or `add_filter` ? ---- Also, notice I used three `$query->set` above - does so many `$query->set` result in a slow website ? – stadisco Oct 20 '14 at 17:14
  • 3
    `add_action` vs `add_filter` has no effect on speed. The exact same process is being performed. You're using the set method. If those are the options you need to set then that's what you need to do. You can't somehow combine them into a call. I'd have to look at the set method to be sure but I can't see it having any impact on performance (excluding the database query that is ultimately run of course). – Nathan Dawson Oct 20 '14 at 17:38