Recently I’ve been working with a client that wanted me to create a way to sort recipes into different types of food and under different types of dishes. This had me thinking about custom fields where you have meta_key and meta_value for each key. The client also wanted to use this in other scenarios so basically i started thinking it should be sorted on categories as well. The function takes one argument which is the category slug, it will then loop through meta_keys belonging to that category, secondly the meta_values and third each posts matching that specific value.
It’s a whole new take on the custom field principle, since you basically start with the meta_key and not the post itself. Probably not the prettiest code in the world, but it does the job:) And it uses definition lists which is ideal here, below the function there’s a css example aswell.
To use this code, put it in your theme’s functions.php and fetch it in your desired template with
function cfMenu($catID) {
global $wpdb, $post;
$catID = get_cat_id('Mat');
$queryKey = "SELECT DISTINCT meta_key FROM $wpdb->postmeta
LEFT JOIN $wpdb->term_relationships AS tr ON $wpdb->postmeta.post_id = tr.object_id
LEFT JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE SUBSTRING(meta_key,1,1) != '_' AND tt.term_id = '$catID'";
$cfKeys = $wpdb->get_results($queryKey, OBJECT);
echo '<div id="cfMenu">';
foreach ($cfKeys as $cfKey) {
echo '<dl>';
echo '<h3 class="cfKey">'.$cfKey->meta_key.'</h3>';
$queryValue = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = '$cfKey->meta_key'";
$cfValues = $wpdb->get_results($queryValue, OBJECT);
foreach ($cfValues as $cfValue) {
echo '<dt class="cfValue">'.$cfValue->meta_value.'</dt>';
$cfPosts = get_posts('meta_value='.$cfValue->meta_value);
foreach ($cfPosts as $cfPost) {
$permalink = get_permalink($cfPost->ID);
echo '<dd class="cfTitle">» <a href='.$permalink.'>'.$cfPost->post_title.'</a></dd>';
}
}
echo '</dl>';
}
echo '</div>';
}
Here’s a CSS example to get you started
#cfMenu {
float: left;
display: inline;
}
#cfMenu h3 {
margin: 0 0 0 0;
padding: 0 0 0 0;
}
#cfMenu dl {
float: left;
width: 230px;
margin-right: 10px;
margin-bottom: 20px;
}
#cfMenu dt {
font-weight: bold;
margin: 5px 0 0 0;
padding: 0 0 0 10px;
}
#cfMenu dd {
margin: 0 0 2px 0;
padding: 0 0 0 10px;
font-size: 90%;
}