获取WordPress帖子类型的所有父分类法


Get all parent taxonomies of a WordPress post type

我的问题与此类似,我自己使用了该技术,但不知道我哪里出错了,所以让我们看看代码。

目的:获取为选择字段设置的选项集中所有父分类的列表

<option value="parent-cat-1">Parent Category 1</option>
<option value="parent-cat-2">Parent Category 2</option>
<option value="parent-cat-3">Parent Category 3</option>

这是PHP代码:

      $taxonomy_names = get_object_taxonomies( $atts['post_type']);
     $args = array('post_type' => $atts['post_type']);
       query_posts($args); 
foreach ($taxonomy_names as $taxonomy_name) {
           if ( have_posts() ) : while ( have_posts() ) : the_post();
       $terms     = get_the_terms( $post->ID, $taxonomy_name );
        foreach( $terms as $term ) {
            $parent_term = get_term( $term->parent, $taxonomy_name );
            $term_list  .= $parent_term->name . ', ' ;
            }  
           var_dump($terms);
               endwhile; endif; wp_reset_query();
               echo $term_list;
}

var_dump($terms);显示string(2) ", " string(4) ", , " string(18) ", , Category 1, , "

var_dump($parent_term); shows object(WP_Error)#980 (2) { ["errors":"WP_Error":private]=> array(1) { ["invalid_term"]=> array(1) { [0]=> string(10) "Empty Term" } } ["error_data":"WP_Error":private]=> array(0) { } } object(WP_Error)#1924 (2) { ["errors":"WP_Error":private]=> array(1) { ["invalid_term"]=> array(1) { [0]=> string(10) "Empty Term" } } ["error_data":"WP_Error":private]=> array(0) { } } object(WP_Error)#1924 (2) { ["errors":"WP_Error":private]=> array(1) { ["invalid_term"]=> array(1) { [0]=> string(10) "Empty Term" } } ["error_data":"WP_Error":private]=> array(0) { } } 

我会考虑将所有这些东西包装在一个函数中,更好。

谢谢

<select class="input-form"  size="1" name="what" required>
<option disabled selected>Выбрать</option>
<?php
$taxonomies  = get_taxonomies(array(
'object_type' => ['advert']
), 'objects');
foreach( $taxonomies as $cur_term ){
echo '<option value="' . $cur_term -> name . '">' . $cur_term -> label . '</option>';
}
?>
</select>