D
D
Danil Ostapenko2021-07-03 10:13:42
WordPress
Danil Ostapenko, 2021-07-03 10:13:42

How to add new parameters to WP_Query()?

For example, on a page in a custom template, there is a simple query with a simple loop:

$args = array(
        'post_type' => 'objects'
    );
    
    $query = new WP_Query( $args );
    while ( $query->have_posts() ) {
        $query->the_post(); 
        the_title(); 
    }

Now the question is, if an additional variable appears, and the condition is triggered, for example:

if(empty($test)==FALSE) {
        $args = array(
            'posts_per_page' => 2
        );
    }

How to combine several variables into one final query (there will be a number of parameters that need to be added to the query if there are variables), so that the result is one combined query?

PS In the Internet, I found options for how to combine 2 requests into one, but you need to glue the parameters into one request. I also found options to glue through a function and a global variable, but I need to add parameters to a new request.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Zolin, 2021-07-03
@Arh1diablo

$args = [
  'post_type' => 'objects'
];

// добавляем в массив параметр по условию
if ( $test ) {
  $args['posts_per_page'] = 2;
}

// запрос
$query = new WP_Query( $args );

-
----, 2021-07-03
@stalkerxxl

array_merge?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question