How does one perform a sub query with different post types

admin2025-06-05  2

I am creating an application for a home cleaning service using the WP API.

I have two custom post types called property and job.

The property posts contain a list of home addresses and phone numbers. The job posts contain active jobs assigned to a property.

When creating a job post, the editor must enter a property_id value so that the job can be associated with a property from the properties list via this foreign key. The property_id refers to the ID from the property post type.

I have a rest route defined to search for all jobs based on the phone number of the property. Currently I am performing two separate wp_query operations which is working.

  • First, to fetch all properties with the phone number matching "1234".
  • Then, fetch all jobs where the property_id matches the results from the first operation.

I understand that this is not a viable solution nor a process friendly one. Is there a way to get the same result by using only one wp_query operation?

My lists can be represented like this:

# Properties
-------------------
ID    phone
1     1234
2     9999
3     5555
-------------------

# Jobs
-------------------
ID    property_id
1     1
2     1
3     2
4     3
-------------------

And, using a hard-coded phone value, my current function looks like this:

# get all properties with the phone number '1234'
$wp_query1 = get_posts([
    'post_type' => ['property'],
    'meta_query' => array(
        'key' => "phone",
        'value' => "1234",
        'compare' => 'LIKE'
    )
]);

# place property ids into an array
foreach($wp_query1 as $post):
    $property_ids[] = $post->ID;
endforeach;

# get all jobs with property ids
$wp_query2 = new WP_Query([
    'post_type' => ['job'],
    'meta_query' => array(
        'key' => "property_id",
        'value' => $property_ids,
        'compare' => 'IN'
    )
]);

# place job ids into an array
foreach($wp_query2 as $post):
    $job_ids[] = $post->ID;
endforeach;

# return job ids
return rest_ensure_response($job_ids);

Thanks

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749081634a316201.html

最新回复(0)