0

I use $_POST form to get multiple elements from a form. The main problem is when I have multiple "if statements". It can become a true mess with nested statements when I want to check if multiple strings exist...

$cat = // Categories

if(!empty($cat)) {
   $args = array(  
    'post_type' => 'domains',
    'post_status' => 'publish',
      'tax_query' => array(
          array (
              'taxonomy' => 'domain_categories', 
              'field' => 'slug',
              'terms' => $cat, // ELEMENT EXISTS FOR $cat
          ),
      ), 
); 
} else { // ELSE STATEMENT IF $cat DOESN'T EXIST
    $args = array(  
        'post_type' => 'domains',
        'post_status' => 'publish',
    );
} // END STATEMENT FOR $cat

So, I would like to be able to simplify this.

0

As said here : Conditional arguments for WP_Query and tax_query depending on if $somevar has a value

I can define the args outside of the WP_Query instantiation:

<?php
$tax_query = array('relation' => 'AND');
    if (isset($search_course_area))
    {
        $tax_query[] =  array(
                'taxonomy' => 'course-area',
                'field' => 'id',
                'terms' => $search_course_area
            );
    }
    if (isset($search_course_level))
    {
        $tax_query[] =  array(
                'taxonomy' => 'study-levels',
                'field' => 'id',
                'terms' => $search_course_level
            );
    }
    if (isset($search_course_mode))
    {
        $tax_query[] =  array(
                'taxonomy' => 'course-mode',
                'field' => 'id',
                'terms' => $search_course_mode
            );
    }

$query = new WP_Query(
    array(
        //Retreive ALL course posts
        'post_type' => 'course',
        'posts_per_page' => '-1',
        //Filter taxonomies by id's passed from course finder widget
        'tax_query' => $tax_query,
    )
);
?>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.