Home › Forums › General Issues › Query posts through relationships' taxonomies › Reply To: Query posts through relationships' taxonomies
So I actually went with $wpdb
because I can combine that with some additional requirements I had. Here’s the query I ended up with:
$category_slug = $_GET["category"];
if($category_slug) {
$category_query = $wpdb->prepare("AND wp_terms.slug = %s", $category_slug);
} else {
$category_query = "";
}
$event_dates_query = <<<EOD
SELECT event_dates.*, $wpdb->terms.name AS category_name
FROM $wpdb->posts AS event_dates
INNER JOIN $wpdb->postmeta AS acf_event
ON acf_event.meta_key = 'event'
AND acf_event.post_id = event_dates.ID
INNER JOIN $wpdb->postmeta AS acf_date
ON acf_date.meta_key = 'date'
AND acf_date.post_id = event_dates.ID
INNER JOIN $wpdb->posts AS events
ON events.ID = acf_event.meta_value
INNER JOIN $wpdb->term_relationships
ON $wpdb->term_relationships.object_id = events.ID
INNER JOIN $wpdb->term_taxonomy
ON $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
INNER JOIN $wpdb->terms
ON $wpdb->term_taxonomy.term_id = wp_terms.term_id
WHERE (acf_date.meta_value >= %s
AND acf_date.meta_value < %s)
AND event_dates.post_type = 'event_date'
AND event_dates.post_status = 'publish'
$category_query
GROUP BY event_dates.ID
ORDER BY acf_date.meta_value ASC;
EOD;
$event_dates = $wpdb->get_results(
$wpdb->prepare($event_dates_query,
$first_day_of_month,
$last_day_of_month));
Besides joining various term-taxonomy-meta-tables I also filter the EventDate
s by their date, so I can paginate them by month.
So there’s quiet an ugly query sitting in my template now, but I think in terms of performance and lines of (php) code written that’s the best I can hope for here.
Based on this query I was also able to build a fulltext search where I query for attributes and meta-keys of Event
s and get back their related EventDate
s quiet easily, so thats nice too.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.