To query events with more than 3 tickets using a single WP_Query
, you will need to perform a custom query that joins the wp_posts
and wp_postmeta
tables to fetch the data
$args = array(
'post_type' => 'event',
'posts_per_page' => -1, // Retrieve all events
'meta_query' => array(
array(
'key' => 'event_id', // Meta key for the event ID in tickets
'compare' => 'EXISTS', // Check if the event ID meta exists
),
),
'fields' => 'ids', // Retrieve only post IDs to improve performance
);
$events_query = new WP_Query($args);
if ($events_query->have_posts()) {
$events_with_tickets = array();
// Loop through events
foreach ($events_query->posts as $event_id) {
// Count the number of tickets associated with each event
$ticket_count = count(get_posts(array(
'post_type' => 'ticket',
'meta_query' => array(
array(
'key' => 'event_id',
'value' => $event_id,
),
),
'fields' => 'ids', // Retrieve only post IDs to improve performance
)));
// If the event has more than 3 tickets, add it to the result array
if ($ticket_count > 3) {
$events_with_tickets[] = $event_id;
}
}
// Now $events_with_tickets contains the IDs of events with more than 3 tickets
// You can perform additional actions with these event IDs if needed
} else {
// No events found
}