我需要列出包含关联自定义字段条目的特定自定义字段项。例如,自定义字段命名为“type”和“food”。我想列出所有的早餐食品。“早餐”是“类型”自定义字段,“培根”、“鸡蛋”、“饼干”是“食物”。现在,我有这个查询,但它列出了我需要的每种食物,而只列出了早餐类型。我是否需要在某处添加“WHERE meta\\u value=\'type\'和meta\\u key=\'breakfast\'”?我试过几个地方,都不管用。
<?php
$metakey = \'type\';
$stocktypes = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
if ($stocktypes) {
foreach ($stocktypes as $stocktype) {
echo "<option value=\\"" . $stocktype . "\\">" . $stocktype . "</option>";
}
}
?>
最合适的回答,由SO网友:Shazzad 整理而成
好的,如果我清楚地理解你,那么这就是解决方案
// first get the post ids that have the breakfast food type
$post_ids = $wpdb->get_col( "SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = \'type\' AND meta_value=\'Breakfast\'" );
// now get the food names
$stocktypes = $wpdb->get_col( "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = \'food\' AND post_id IN (". implode(\',\', array_map(\'absint\', $post_ids) ) .")" );
if ($stocktypes) {
foreach ($stocktypes as $stocktype) {
echo "<option value=\\"" . $stocktype . "\\">" . $stocktype . "</option>";
}
}