I have a custom post type, Album, which has a custom field called ‘tracklist’. Tracklist is a multidimensional array which contains a track title and track link, like so:
$tracklist = array(
[0] => array(
[title] => 'Stairway to Heaven'
[link] => 'stairway.mp3'
)
[1] => array(
[title] => 'Battle of Evermore'
[link] => 'battle.mp3'
)
);
I want to use get_posts to find all the albums with the song ‘Stairway to Heaven.’ Something like this (I know this won’t work, but hopefully it will explain my intentions):
$albums = get_posts(array(
'post_type' => 'collection',
'meta_query' => array(
array(
'key' => 'tracklist',
'value' => array(
'key' => 'track'
'value' => array(
'key' => 'title',
'value' => 'Starway to Heaven'
)
)
)
)
));
It’s easy enough to use meta_query to look for a custom field that returns a single string, but in this case I’m looking a for a value buried a few levelsdeep. How would I do this?
You can’t, at least not efficiently. You best bet is to use the
LIKE
statement, but it would fail for searches like “title”, “link”, “mp3” 🙂I suggest you build your own serialization method. For example, store the tracklist as a string like this:
Notice the new line character (
n
). Use it to split the string into an array when you need to use the meta value.Then you can have something like:
The download links can go into a separate meta record.