admin管理员组

文章数量:1122846

I have two post types - Ticket and Event

Each ticket has a meta called 'event_id' which connects it to an Event.

Suppose I want to fetch all events with more than 3 tickets. I want to do it in a single WP_Query so that the results can be paginated properly. How can I do this?

I have two post types - Ticket and Event

Each ticket has a meta called 'event_id' which connects it to an Event.

Suppose I want to fetch all events with more than 3 tickets. I want to do it in a single WP_Query so that the results can be paginated properly. How can I do this?

Share Improve this question asked Mar 31, 2024 at 16:17 mrkarma4yamrkarma4ya 1 1
  • Can you include the code you're currently trying to accomplish this with? – Tony Djukic Commented Apr 1, 2024 at 0:54
Add a comment  | 

1 Answer 1

Reset to default 0

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
}

本文标签: wp queryQuering a post object based on another related post object