Reece
Reece

Reputation: 2701

How to filter content?

I am setting up a property page with advanced custom fields and custom post types. I need to be able to filter the properties by number of bedrooms, price, location etc. I have been able to filter the properties by number of bedrooms but I cannot figure out how to apply two filters at the same time. For example I created a acf field called test and it has the values; one, two and three. Now I want to display a property that has 5 bedrooms and a test value of three. How can I change my code to do this?

$GLOBALS['my_query_filters'] = array( 
'field_1'   => 'bedrooms', 
'field_2'   => 'test',
);

add_action('pre_get_posts', 'my_pre_get_posts');

function my_pre_get_posts( $query ){
// bail early if is in admin
if( is_admin() ){
    return;
} 

// get meta query
$meta_query = $query->get('meta_query');

foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
    if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'property' ) {
        if( isset($_GET[ $name ]) ){
            $value = explode(',', $_GET[ $name ]);

            $meta_query[] = array(
                'key'        => $name,
                'value'      => $value,
                'compare'    => 'IN',
            );
        }
    }
}

// update meta query
$query->set('meta_query', $meta_query);

return;
}

Upvotes: 0

Views: 64

Answers (1)

Anand Choudhary
Anand Choudhary

Reputation: 565

You can directly run these query in your templates files where you want to display your custom posts. you can also add more fields after relation AND in defaults variable .

<?php 

$defaults = array(
    'numberposts' => -1,
    'category' => 0, 'orderby' => 'date',
    'order' => 'DESC', 'include' => array(),
    'exclude' => array(),'post_type' => 'your_custom_post_type',
    'meta_key','meta_value',
    'meta_query' => array(
    'relation' => 'AND',
    array(
    'key'     => 'custom_field_name1',
    'value'   => $custom_field_value1,
    ),
    array(
    'key'     => 'custom_field_name2',
    'value'   => $custom_field_name2,
    )
));

$query = get_posts($defaults);
?>

Upvotes: 1

Related Questions