Support

Account

Home Forums ACF PRO wp query with multiple relation keys Reply To: wp query with multiple relation keys

  • This is completely untested and just written in text editor on my lunch break but this is how I would start handling this.

    $args = array(
        'post_type'  => 'cp_course',
        'numberposts' =>-1,
        'orderby' => 'ID',
        'order' => 'ASC',
        'meta_query' =>
            array(
                'relation' => 'AND',
            )
    
    );
    
    if($searchterm) {
        $args['s'] = $searchterm;
    }
    
    if($code) {
        $code_args = array(
            'key'   => 'course_code',
            'value' => $code,
        );
        $args = array_push($code_args ,$args['meta_query'] );
    }
    
    if($duration) {
        $dur_args = array(
            'key' => 'course_duration',
            'value' => $duration,
        );
        $args = array_push($dur_args ,$args['meta_query'] );
    }
    
    if($datefrom) {
        $from_args = array(
            'relation' => 'OR',
            array(
                'key'   => 'period_a_start',
                'compare' => '>=',
                'type' => 'numeric',
                'value' => date("Ymd", strtotime($datefrom)),
            ),
            array(
                'key'   => 'period_b_start',
                'compare' => '>=',
                'type' => 'numeric',
                'value' => date("Ymd", strtotime($datefrom)),
            ),
            array(
                'key'   => 'period_c_start',
                'compare' => '>=',
                'type' => 'numeric',
                'value' => date("Ymd", strtotime($datefrom)),
            ),
            array(
                'key'   => 'period_d_start',
                'compare' => '>=',
                'type' => 'numeric',
                'value' => date("Ymd", strtotime($datefrom)),
            ),
        );
        $args = array_push($from_args ,$args['meta_query'] );
    }
    
    if($dateto) {
        $to_args = array(
            'relation' => 'OR',
            array(
                'key'   => 'period_1_end',
                'compare' => '<=',
                'type' => 'numeric',
                'value' => date("Ymd", strtotime($dateto)),
            ),
            array(
                'key'   => 'period_b_end',
                'compare' => '<=',
                'type' => 'numeric',
                'value' => date("Ymd", strtotime($dateto)),
            ),
            array(
                'key'   => 'period_c_end',
                'compare' => '<=',
                'type' => 'numeric',
                'value' => date("Ymd", strtotime($dateto)),
            ),
            array(
                'key'   => 'period_d_end',
                'compare' => '<=',
                'type' => 'numeric',
                'value' => date("Ymd", strtotime($dateto)),
            ),
    
        );
        $args = array_push($to_args ,$args['meta_query'] );
    }