Filter result of Custom Post Type using meta_query with ACF

Question

Im using a custom post type named property to list some houses and flats. In this cpt, I have multiple custom fields from Advanced Custom Fields plugin, such as localization, price, rooms and so on. This is the HTML form I’m using to filter the results using GET method

<form>
  <button type="submit">filter</button>
  
  <select name="orderby" id="">
    <option value="" disabled selected>Order by:</option>
    <option value="all">All</option>
    <option value="ASC">Lower price</option>
    <option value="DESC">Higher price</option>
  </select>

  <h3>Type of contract</h3>
  <select name="contract">
    <option value="" selected disabled>Select an option</option>
    <option value="rent">Rent</option>
    <option value="for_sale">For sale</option>
  </select>
  ...
</form>

In my loop I have this array, based on Codex. I’m using an example of nested arrays, did not work.

<?php 
  $args = array(
    'post_type' => 'property',
    'posts_per_page' => -1,
    'meta_key' => 'price',
    'orderby' => 'meta_value_num',
    'order' => $_GET['orderby'],
    'meta_query' => array(
       'relation' => 'AND',
           array(
              array(
                 'key'   => 'contract',
                 'value' => $_GET['contract'],
                 'compare' => '='
              ),
          array(
                 'key'   => 'rooms',
                 'value' => $_GET['rooms'],
                 'compare' => '='
          ),
          ...
          $query = new WP_Query($args);
             if($query->have_posts()) : while($query->have_posts()) : $query->the_post()
          ...

So for the listing of cpt based on this form as a filter using GET parameters, also ordering price by ASC or DESC, what should I do?

0
Luan Piegas 1 month 0 Answers 6 views 0

Leave an answer