我制作了两个自定义函数来获取项目中的父子类别。
创建一个名为 project-helper.php 的文件并转到 functions.php,最后添加您创建的 project-helper.php 文件到 functions.php
//functions.php
require 'project-helper.php';
// project-helper.php
/**
* Get Category
* @param $taxonomy
* @param string $order
* @return array
*/
function getPostTermCategory($taxonomy, $order = 'asc')
{
$term_query = new WP_Term_Query([
'taxonomy' => $taxonomy,
'order' => $order,
'hide_empty' => false,
'parent' => 0
]);
$categories = [];
foreach ($term_query->terms as $term) {
$categories[] = $term;
}
return $categories;
}
/**
* Get Child Categories of Parent
* @param $taxonomy
* @param $parentId
* @param string $order
* @return array
*/
function getPostTermChildCategory($taxonomy, $parentId, $order = 'asc')
{
$term_query = new WP_Term_Query([
'taxonomy' => $taxonomy,
'order' => $order,
'hide_empty' => false,
'parent' => $parentId
]);
$categories = [];
foreach ($term_query->terms as $term) {
$categories[] = $term;
}
return $categories;
}
现在从您的模板中调用创建的函数。
$projectRegions = getPostTermCategory('project-region-cat');
foreach ($projectRegions as $projectRegion) {
<?php $categoryChild = getPostTermChildCategory('project-region-cat', $projectRegion->term_id);
foreach ($categoryChild as $categoryChild) { ?>
<option value="<?= $categoryChild->slug; ?>"><?= $categoryChild->name; ?></option>
<?php } ?>
}
我使用了 select html 标记的 option。你可以用你的循环做任何事情
//这里project-region-cat是父类