Filter and order post by more custom fields

Question

I have a problem with following code.

I want to filter post by two input checkbox, for example a and b, and order the result by meta value (contained in relevant post as meta value num).

The problem is when both input are selected, because in this case I’d like to combine all result and order them by a third meta value (for example c).

If input A is selected, I want to filter and order by meta value a;
If input B is selected, I want to filter and order by meta value b;
If both input A and B are selected, I want combine all result of a and b and order them by meta value c;

First two option works, for the third I have problem.

I’m not able to combine all results of meta value a and b and order them by meta value c.

Here my code:

function my_filter_function(){
    $args = array(
        'post_type' => 'custom_post_type',
        'orderby' => 'meta_value_num'       
    );
        // if both A and B are set
    if( (isset( $_POST['a'] ) && $_POST['a'] == 'on') && (isset( $_POST['b'] ) && $_POST['b'] == 'on') )
            $args['meta_query'][] = array(
//          'relation'=>'OR',       
            'post_type' => 'custom_post_type',
            'post_status' => 'publish',         
            'key' => 'c',               
            'value' => 0,
            'type' => 'numeric', // specify it for numeric values
            'compare' => '>'        
        );      

    // if only A is set
    if( isset( $_POST['a'] ) && $_POST['a'] == 'on' )
        $args['meta_query'][] = array(
            'post_type' => 'custom_post_type',
            'post_status' => 'publish',         
            'key' => 'a',               
            'value' => 0,
            'type' => 'numeric', // specify it for numeric values
            'compare' => '>'        
        );      

    // if only B is set
    if( isset( $_POST['b'] ) && $_POST['b'] == 'on' )
        $args['meta_query'][] = array(
            'post_type' => 'custom_post_type',
            'post_status' => 'publish',     
            'key' => 'b',
            'value' => 0,
            'type' => 'numeric', // specify it for numeric values
            'compare' => '>',
        );  
0
Giulio 2 months 0 Answers 13 views 0

Leave an answer