Correct way to list multiple $query->set

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

Read More

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' );

Related posts

Leave a Reply

2 comments

  1. The correct way to use the set method (which is part of the WP_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:

    $query->set( 'category__not_in', array(60, 61) );
    

    For more information about category query parameters, check http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

  2. Alternatively, for a more elegant and concise approach. You could group them in an array and loop through them.

    <?php
    
    $query_vars = array(
        'post_type' => 'question',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'posts_per_archive_page' => 1,
        'orderby' => 'rand(' . get_query_var( 'docket' ) . ')',
    );
    
    foreach ( $query_vars as $key => $value ) {
    
        $wp_query->set( $key, $value );
    
    };