What is the correct way to list multiple $query->set ? Am I allowed to have multiple $query->set
like “CODE A” below ?
Or am I supposed to combine them into one? If yes, how would you combine the three $query->set
code? I tried combining them in “CODE B” below but it didn’t work.
.
CODE A: Before combine $query->set
This code goes in functions.php
function featured_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'category_name', 'new' );
$query->set( 'cat', '-60, -61' );
$query->set( 'posts_per_page', 5 );
}
}
add_action( 'pre_get_posts', 'featured_category' );
.
CODE B: After combine $query->set
This code goes in functions.php
function featured_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( array( 'category_name' => 'new', 'cat' => '-60, -61', 'posts_per_page' => 5) );
}
}
add_action( 'pre_get_posts', 'featured_category' );
The correct way to use the
set
method (which is part of theWP_Query
class) is to pass 2 parameters – a query parameter key and a query parameter value. So your first example (CODE A) is the correct way to do it.You can take a look at the method code here: https://core.trac.wordpress.org/browser/tags/4.0/src/wp-includes/query.php#L2328
P.S.
If you want to exclude multiple categories from a query, consider using the
category__not_in
query parameters, for example:For more information about category query parameters, check http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
Alternatively, for a more elegant and concise approach. You could group them in an array and loop through them.