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
1 Answer
Reset to default 0To 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
版权声明:本文标题:wp query - Quering a post object based on another related post object 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736312144a1934993.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论