Sunday, 18 August 2013

wordpress ajax relationship query

wordpress ajax relationship query

Using the relationship field from Advanced Custom Fields I link artists to
events. Both these artist and events are custom post types. For each
event, the post IDs of the related artists are stored in an array as a
custom meta field (lineup_artists).
On each event page I list all the artists. When you click on an artist,
I'd like to show all the events where you can find this artist (through an
AJAX call which shows the results in a bootstrap modal). I've tested the
AJAX call and it's working, but there's something wrong with the query
(takes very long to complete).
In my function I have:
$ArtistID = $_POST['ArtistID']; // Gets the ArtistID from the AJAX call
$meta_query = array(
'key' => 'lineup_artists',
'value' => '"' . $ArtistID .'"',
'compare' => 'LIKE'
);
$args = array(
'post_type' => 'events',
'meta_query' => array($meta_query),
'posts_per_page' => 5,
'post_status' => 'publish',
);
If I dump the results of wp_query, I get the following sql query:
SELECT SQL_CALC_FOUND_ROWS yt_posts.ID FROM yt_posts
INNER JOIN yt_postmeta ON (yt_posts.ID = yt_postmeta.post_id)
WHERE 1=1
AND yt_posts.post_type = 'events'
AND (yt_posts.post_status = 'publish')
AND ( (yt_postmeta.meta_key = 'lineup_artists' AND
CAST(yt_postmeta.meta_value AS CHAR) LIKE '%\"17497\"%') )
GROUP BY yt_posts.ID ORDER BY yt_posts.post_date DESC LIMIT 0, 5
When I paste this query in phpmyadmin it takes very long to complete (I've
never seen it finish because it takes so long).
Is this because the artist IDs are stored as an array? Someone told me
that this is not very efficient and that these relations should be stored
in a separate table (which I don't know how to do). Is there something
wrong with my query or is this a very inefficient way of querying
relations?

No comments:

Post a Comment