0

I would like to implement a search function where a user can enter an amount($amount) and based on that argument the search result needs to show all posts where $amount >= loan_min (meta key) AND $amount <= loan_max (meta key)

Let's suppose we have a post that has meta keys loan_min=100 and loan_max=500 then say entering 200 in search will show this post but if a user enters 50 or 550 in search then this post will not be showing in the result.

Here is how it is coded.

$meta_query =   array(  
                                    
                                            'relation' => 'AND',
                                        array( 
                                                 
                                                'key'      => 'minimum_loan_amount',
                                                'value'    =>  $loan_amount_requested,
                                                'type'     => 'numeric',
                                                'compare'  => '>='
                             
                                            ),
                                            array( 
                                                 
                                                'key'      => 'maximum_loan_amount',
                                                'value'    =>  $loan_amount_requested,
                                                'type'     => 'numeric',
                                                'compare'  => '<='
                             
                                            )
                                                    
                            );

1 Answer 1

0

By passing the meta key parameters. you can filter you posts.

$args = array(
'post_type'  => 'post_type',(optional)
'meta_key'   => 'age',
'meta_query' => array(
    array(
        'key'     => 'loan_min',
        'value'   => $amount,
        'compare' => '>=',
    ),
    array(
        'key'     => 'loan_min',
        'value'   => $amount,
        'compare' => '<=',
    ),
),

);

$query = new WP_Query( $args );

You can try with this code. For more query you can visit this site: https://rudrastyh.com/wordpress/meta_query.html

1
  • I already tried this but for some reason, it's not working, Although a single meta key is working, using both meta keys with AND is not working. I updated the question with the code I'm usnig.
    – Ahmad Khan
    Commented Aug 2, 2022 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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