如何获取自定义帖子类型的父项和子项。我下面有部分工作的代码,问题是它不会在相同的div中生成子项和父项,而是在循环中生成不同的div。由于缺乏有关PHP的知识,我不确定如何解决它。
如果我有父母和孩子,我想要什么;
- USA
- New York
结果应该是
USA, New York
但使用以下代码,它生成为
,USA
,New York
代码;
<div class="address">
<?php
$terms = get_terms(array(
'taxonomy' => 'people-country',
'hide_empty' => false,
));
?>
<?php foreach ($terms as $term) : ?>
<?php
$re = explode('-', $term->name);
$args = array (
'post_type' => 'people', //
'posts_per_page' => 2,
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'people-country',
'field' => 'id',
'terms' => $term->term_id,
),
),
);
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$title = get_the_title();
// $info = get_post_meta(get_the_ID(), '_post_info', true);
// $link = get_term_meta($term->term_id, 'link', true);
?>
<div class="text">
<span class="number"><?php echo ",".$re[0] ?>
</span>
</div>
<?php
}
}
endforeach; ?>
</div>
答案 0 :(得分:1)
我只是通过使用以下代码对其进行更改来解决它;
<?php
$cats = get_the_terms(get_the_ID(), 'people-country');
$names = array();
if ($cats) foreach ($cats as $cat) {
if ($cat->parent) {
array_push($names, $cat->name);
}
}
if ($cats) foreach ($cats as $cat) {
if (!$cat->parent) {
array_push($names, $cat->name);
}
}
?>
<?php echo implode(', ', $names) ?>