Get Custom Field Values by Another Custom Field in WordPress

I have a custom post type named houses.
Inside this post type I have several custom fields, like:

(name – field type – meta key)

  • Title (wordpress field)
  • City (taxonomy – city)
  • Condominium (custom post type – condominium)
  • Beach (custom post type – beach)
  • Country (taxonomy – country)
  • Description (custom field – description)
  • Text (custom field – text)
  • Bedrooms (custom field – bedrooms)
  • Bathrooms (custom field – bathrooms)
  • Type (taxonomy – type)
  • Status (taxonomy – status)
  • Area (custom field – area)
  • Full Area (custom field – full_area)
  • Place (taxonomy – place)

and more.

I have a plugin on my website with 4 selects:

  • City
  • Beach
  • Type
  • Status

What I need to do is, update these selects when I select an option.

For example, if I select Barcelona for City and Sale for Status, I need to retrieve all Types and Beaches with these options in common.

I don’t need to get the posts now, just update the select options, like a filter.

Here an example:

Filter with selects

PS: I’m using Advanced Custom Fields.

1 Answer
1

After struggling with this, I found a workaround that worked.

Since every custom field has a connection with my custom post type, I was able to use wp_get_object_terms to get the terms for each custom taxonomy.

Using the query to retrieve all posts:

$args = array(
   'post_type' => 'houses'
);
$houses = new WP_Query($args);
$posts = $houses->posts;

// get an array with all ID fields
$my_post_ids = wp_list_pluck($posts, 'ID');

After that I can get the terms for these IDs above:

$city_terms = wp_get_object_terms($my_post_ids, 'cities');
$status_terms = wp_get_object_terms($my_post_ids, 'status');
$type_terms = wp_get_object_terms($my_post_ids, 'type');

And to have the behavior I needed when an option is selected in order to refresh the selects information, I had just to update the query for that. For example, if I selected some city:

$args = array( 
  'post_type' => 'houses',
  'meta_query' => array(
    'relation' => 'AND',
      array(
        'key' => 'city',
        'value' => 107,
        'compare' => 'LIKE'
      )
    )
);

To do the filter, just need to add a new relation inside the meta_query array.

$args = array( 
  'post_type' => 'houses',
  'meta_query' => array(
    'relation' => 'AND',
      array(
        'key' => 'city',
        'value' => 107,
        'compare' => 'LIKE'
      ),
      array(
        'key' => 'status',
        'value' => 80,
        'compare' => 'LIKE'
      )
    )
);

All of this combined with Ajax to make the data update for each select.

Leave a Comment