Home › Forums › General Issues › How to create a dynamic WP query using nested if / foreach statements
I am trying to create a dynamic WP query based on custom fields in a page but cannot work out how to do it without syntax errors.
Can anybody advise on the approach to take to achieve this sort of thing, am I getting it completely wrong?
See below my code and an example of the desired query to be built from the custom fields…
Here is my code:
if( have_rows('query') ):
while( have_rows('query') ): the_row();
$query_name = get_sub_field('query_name');
$queries= get_sub_field ('queries');
if( $queries ) {
foreach( $queries as $query ) {
$created_queries= $query['create_query'];
if( $created_queries ) {
foreach( $created_queries as $created_query ) {
$type= $created_query['statement_type'];
$rules= $created_query['rules'];
if( $rules ) {
foreach( $rules as $rule ) {
$key= $rule['key'];
$operator= $rule['operator'];
$value=$rule['value'];
}
}
}
$query_name = array(
'post_type' => 'candidates',
'meta_query' => array(
'relation' => $type ,
array(
'key' => $key,
'value' => $value,
'compare' => $operator,
),
),
);
$test = new WP_Query( $query_name );
echo $query_name, $test-post_count;
}
}
}
endwhile;
endif;
Example of desired output:
$args_red = array(
'post_type' => 'candidates',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'available_for_current_start_date',
'value' => 'N',
'compare' => '=',
),
array(
'key' => 'start_date_difference',
'value' => '7',
'compare' => '<='
),
'relation'=> 'AND',
array(
'key' => 'forename',
'value' => 'test',
'compare' => '=',
),
),
);
$red = new WP_Query( $args_red );
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.