我使用 Wordpress 类别按城市创建公司目录。
类别是城市。
自定义字段是包含城市的区域。
对于使用的自定义字段 - Advanced Custom Fields
用于构建自定义分类顺序 - WP Term Order
$terms = get_terms( 'catalog_categories', array(
'depth' => 1,
'number' => 100,
'parent' => 0,
'orderby' => 'taxon_name', // order array name
'order' => 'DESC',
'hide_empty' => false,
'meta_query' => array(
'taxon_name' => array(
'key' => 'taxon' // acf custom field name
) )
) );
foreach ($terms as $key => $object) {
$region = get_field('taxon', $object);
echo $region . ' ' . $object->name . '<br>';
}
我收到:
Wielkopolskie 波兹南
Wielkopolskie 博亚诺沃
Mazoweckie 华沙
多诺斯拉斯基弗罗茨瓦夫
多诺斯拉斯基贾沃尔
但是我需要:
Wielkopolskie
——波兹南
——博亚诺沃
Mazoweckie
——华沙
多诺斯拉斯基
——弗罗茨瓦夫
——贾沃尔
请帮助决定这个问题
更新
*帮助请在代码中添加指向 Wordpress 类别的链接(slug)
这里我们收集了一个地区的所有城市:
$collection[$region][] = $object->name;
我们需要给每个城市添加一个 slug
$object->slug;
我们需要将其用作选项值的 slug。
'<option value="' . **SLUG** . '" data-select2-id="'. $data_select_id . '-' .$i .'">' . $city . '</option>';
更新 :
*工作代码
我们添加到 - $collection[$region][] = $object->name; - $object->slug 并将它们组合成一个数组
$collection[$region][] = array('name' => $object->name, 'slug' => $object->slug);
对于我们使用的输出 - $city['name'] 和 $city['slug']
<?php
$terms = get_terms( 'catalog_categories', array(
'depth' => 1,
'number' => 100,
'parent' => 0,
'orderby' => 'taxon_name', // order array name
'order' => 'DESC',
'hide_empty' => false,
'meta_query' => array(
'taxon_name' => array(
'key' => 'taxon' // acf custom field name
) )
) );
$collection = [];
foreach ($terms as $key => $object) {
$region = get_field('taxon', $object);
if (!isset($collection[$region])) {
$collection[$region] = [];
}
$collection[$region][] = array('name' => $object->name, 'slug' => $object->slug);
}
$data_select_id = 1;
echo '<div>';
foreach ($collection as $region => $cities) {
$i = 0;
echo '<div label="' . $region . '" data-select2-id="' . $data_select_id . '">'. $region;
foreach ($cities as $city) {
$i++;
echo '<option value="' . $city['slug'] . '" data-select2-id="'. $data_select_id . '-' .$i .'">' . $city['name'] . '</option>';
}
echo '</div>';
$data_select_id ++;
}
echo '</div>';
;?>
最佳答案
您可以使用额外的数组将城市分类为如下区域:
$collection = [];
foreach ($terms as $key => $object) {
$region = get_field('taxon', $object);
if (!isset($collection[$region])) {
$collection[$region] = [];
}
$collection[$region][] = $object->name;
}
foreach ($collection as $region => $cities) {
echo $region . '<br/>';
foreach ($cities as $city) {
echo '--' . $city . '<br/>';
}
}
关于php - Wordpress 类别按自定义字段排序(完成)。如何只输出一次自定义字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47981980/