「地理的な場所」と呼ばれる階層的な分類法があります。これには、最初のレベルの大陸が含まれ、次にそれぞれの国が含まれます。例:
Europe
- Ireland
- Spain
- Sweden
Asia
- Laos
- Thailand
- Vietnam
等
get_terms()を使用して、用語の完全なリストを出力することができましたが、大陸は1つの大きなフラットリストで国と混同されます。
上記のような階層リストを出力するにはどうすればよいですか?
「地理的な場所」と呼ばれる階層的な分類法があります。これには、最初のレベルの大陸が含まれ、次にそれぞれの国が含まれます。例:
Europe
- Ireland
- Spain
- Sweden
Asia
- Laos
- Thailand
- Vietnam
等
get_terms()を使用して、用語の完全なリストを出力することができましたが、大陸は1つの大きなフラットリストで国と混同されます。
上記のような階層リストを出力するにはどうすればよいですか?
回答:
引数wp_list_categoriesとともに使用し'taxonomy' => 'taxonomy'ます。階層カテゴリリストを作成するために構築されていますが、カスタム分類の使用もサポートします。
コーデックスの例:
カスタム分類で用語を表示する
リストがフラットに戻って戻ってきた場合、リストにパディングを追加するために少しのCSSが必要なだけなので、階層構造を見ることができます。
これは非常に古い質問ですが、実際の用語の構造を構築する必要がある場合、これはあなたにとって便利な方法かもしれません:
/**
 * Recursively sort an array of taxonomy terms hierarchically. Child categories will be
 * placed under a 'children' member of their parent term.
 * @param Array   $cats     taxonomy term objects to sort
 * @param Array   $into     result array to put them in
 * @param integer $parentId the current parent ID to put them in
 */
function sort_terms_hierarchically(Array &$cats, Array &$into, $parentId = 0)
{
    foreach ($cats as $i => $cat) {
        if ($cat->parent == $parentId) {
            $into[$cat->term_id] = $cat;
            unset($cats[$i]);
        }
    }
    foreach ($into as $topCat) {
        $topCat->children = array();
        sort_terms_hierarchically($cats, $topCat->children, $topCat->term_id);
    }
}
使用法は次のとおりです。
$categories = get_terms('my_taxonomy_name', array('hide_empty' => false));
$categoryHierarchy = array();
sort_terms_hierarchically($categories, $categoryHierarchy);
var_dump($categoryHierarchy);
$into[$cat->term_id] = $cat;を$into[] = $cat;持つことは迷惑であり(0キーを使用して最初の要素を簡単に取得することはできません)、役に立たない(すでに$catオブジェクトを保存していて、idを取得できます)term_idプロパティを使用して
                    私はあなたが望むことをする関数を知りませんが、あなたはこのようなものを構築することができます:
<ul>
    <?php $hiterms = get_terms("my_tax", array("orderby" => "slug", "parent" => 0)); ?>
    <?php foreach($hiterms as $key => $hiterm) : ?>
        <li>
            <?php echo $hiterm->name; ?>
            <?php $loterms = get_terms("my_tax", array("orderby" => "slug", "parent" => $hiterm->term_id)); ?>
            <?php if($loterms) : ?>
                <ul>
                    <?php foreach($loterms as $key => $loterm) : ?>
                        <li><?php echo $loterm->name; ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </li>
    <?php endforeach; ?>
</ul>
私はこれをテストしていませんが、あなたは私が何を得ているか見ることができます。上記のコードが行うことは、2つのレベルのみを提供することです
編集:ああはい、wp_list_categories()を使用して目的の操作を実行できます。
wp_list_categories()、GETパラメーターを追加することもできます。または、必要なビットを追加するための関数のフィルターを作成することもできます。私はまだ頭を悩ませることができていないので、どうやってやるのか聞かないでください:(
                    wp_list_categoriesます。これにより、コードがより再利用可能になります
                    私は同じものを探していましたが、1つの投稿の条件を取得するために、最終的にこれをコンパイルしました、それは私のために機能します。
機能:
•特定の投稿の分類名のすべての用語を取得します。
•2つのレベル(例:level1: 'country'とlevel2: 'cities')の階層分類では、level1でh4を作成し、その後にlevel2のulリストとすべてのlevel1アイテムを作成します。
•分類が階層的でない場合、すべてのアイテムのulリストのみが作成されます。ここにコードがあります(私のために書いているので、できるだけ汎用的にしようとしましたが...):
function finishingLister($heTerm){
    $myterm = $heTerm;
    $terms = get_the_terms($post->ID,$myterm);
    if($terms){
        $count = count($terms);
        echo '<h3>'.$myterm;
        echo ((($count>1)&&(!endswith($myterm, 's')))?'s':"").'</h3>';
        echo '<div class="'.$myterm.'Wrapper">';
        foreach ($terms as $term) {
            if (0 == $term->parent) $parentsItems[] = $term;
            if ($term->parent) $childItems[] = $term; 
        };
        if(is_taxonomy_hierarchical( $heTerm )){
            foreach ($parentsItems as $parentsItem){
                echo '<h4>'.$parentsItem->name.'</h4>';
                echo '<ul>';
                foreach($childItems as $childItem){
                    if ($childItem->parent == $parentsItem->term_id){
                        echo '<li>'.$childItem->name.'</li>';
                    };
                };
                echo '</ul>';
            };
        }else{
            echo '<ul>';
            foreach($parentsItems as $parentsItem){
                echo '<li>'.$parentsItem->name.'</li>';
            };
            echo '</ul>';
        };
        echo '</div>';
    };
};
最後に、これで関数を呼び出します(明らかに、my_taxonomyをyoursに置き換えます): finishingLister('my_taxonomy');
私はそれが完璧だとは思わないが、私が言ったようにそれは私のために働く。
次のコードは、用語を含むドロップダウンを生成しますが、$ outputTemplate変数を編集し、str_replace行を編集することにより、他の要素/構造を生成することもできます。
function get_terms_hierarchical($terms, $output = '', $parent_id = 0, $level = 0) {
    //Out Template
    $outputTemplate = '<option value="%ID%">%PADDING%%NAME%</option>';
    foreach ($terms as $term) {
        if ($parent_id == $term->parent) {
            //Replacing the template variables
            $itemOutput = str_replace('%ID%', $term->term_id, $outputTemplate);
            $itemOutput = str_replace('%PADDING%', str_pad('', $level*12, '  '), $itemOutput);
            $itemOutput = str_replace('%NAME%', $term->name, $itemOutput);
            $output .= $itemOutput;
            $output = get_terms_hierarchical($terms, $output, $term->term_id, $level + 1);
        }
    }
    return $output;
}
$terms = get_terms('taxonomy', array('hide_empty' => false));
$output = get_terms_hierarchical($terms);
echo '<select>' . $output . '</select>';  
私はこの問題を抱えていましたが、何らかの理由でここでの答えがうまくいきませんでした。
これが私の更新された動作中のバージョンです。
function locationSelector( $fieldName ) {
    $args = array('hide_empty' => false, 'hierarchical' => true, 'parent' => 0); 
    $terms = get_terms("locations", $args);
    $html = '';
    $html .= '<select name="' . $fieldName . '"' . 'class="chosen-select ' . $fieldName . '"' . '>';
        foreach ( $terms as $term ) {
            $html .= '<option value="' . $term->term_id . '">' . $term->name . '</option>';
            $args = array(
                'hide_empty'    => false, 
                'hierarchical'  => true, 
                'parent'        => $term->term_id
            ); 
            $childterms = get_terms("locations", $args);
            foreach ( $childterms as $childterm ) {
                $html .= '<option value="' . $childterm->term_id . '">' . $term->name . ' > ' . $childterm->name . '</option>';
                $args = array('hide_empty' => false, 'hierarchical'  => true, 'parent' => $childterm->term_id); 
                $granchildterms = get_terms("locations", $args);
                foreach ( $granchildterms as $granchild ) {
                    $html .= '<option value="' . $granchild->term_id . '">' . $term->name . ' > ' . $childterm->name . ' > ' . $granchild->name . '</option>';
                }
            }
        }
    $html .=  "</select>";
    return $html;
}
そして使用法:
$selector = locationSelector('locationSelectClass');
echo $selector;
本当にうまく機能していた@popsiコードを使用し、より効率的で読みやすくしました。
/**
 * Recursively sort an array of taxonomy terms hierarchically. Child categories will be
 * placed under a 'children' member of their parent term.
 * @param Array   $cats     taxonomy term objects to sort
 * @param integer $parentId the current parent ID to put them in
 */
function sort_terms_hierarchicaly(Array $cats, $parentId = 0)
{
    $into = [];
    foreach ($cats as $i => $cat) {
        if ($cat->parent == $parentId) {
            $cat->children = sort_terms_hierarchicaly($cats, $cat->term_id);
            $into[$cat->term_id] = $cat;
        }
    }
    return $into;
}
使用法 :
$sorted_terms = sort_terms_hierarchicaly($terms);それhierarchical=trueがあなたのget_terms()呼び出しに渡されることを確認してください。
hierarchical=trueがデフォルトであることに注意してください。したがって、実際には、オーバーライドされていないことを確認してfalseください。
get_terms()(OPが述べているように)用語の完全なリストを返しますが、要求された親/子関係を示す階層リストは返しません。
                    ここには、最初のアイテムが非表示の4レベルのドロップダウン選択リストがあります
<select name="lokalizacja" id="ucz">
            <option value="">Wszystkie lokalizacje</option>
            <?php
            $excluded_term = get_term_by('slug', 'podroze', 'my_travels_places');
            $args = array(
                'orderby' => 'slug',
                'hierarchical' => 'true',
                'exclude' => $excluded_term->term_id,
                'hide_empty' => '0',
                'parent' => $excluded_term->term_id,
            );              
            $hiterms = get_terms("my_travels_places", $args);
            foreach ($hiterms AS $hiterm) :
                echo "<option value='".$hiterm->slug."'".($_POST['my_travels_places'] == $hiterm->slug ? ' selected="selected"' : '').">".$hiterm->name."</option>\n";
                $loterms = get_terms("my_travels_places", array("orderby" => "slug", "parent" => $hiterm->term_id,'hide_empty' => '0',));
                if($loterms) :
                    foreach($loterms as $key => $loterm) :
                    echo "<option value='".$loterm->slug."'".($_POST['my_travels_places'] == $loterm->slug ? ' selected="selected"' : '')."> - ".$loterm->name."</option>\n";
                    $lo2terms = get_terms("my_travels_places", array("orderby" => "slug", "parent" => $loterm->term_id,'hide_empty' => '0',));
                    if($lo2terms) :
                        foreach($lo2terms as $key => $lo2term) :
                        echo "<option value='".$lo2term->slug."'".($_POST['my_travels_places'] == $lo2term->slug ? ' selected="selected"' : '').">    - ".$lo2term->name."</option>\n";
                        endforeach;
                    endif;
                    endforeach;
                endif;
            endforeach;
            ?>
         </select>
        <label>Wybierz rodzaj miejsca</label>
        <select name="rodzaj_miejsca" id="woj">
            <option value="">Wszystkie rodzaje</option>
            <?php
            $theterms = get_terms('my_travels_places_type', 'orderby=name');
            foreach ($theterms AS $term) :
                echo "<option value='".$term->slug."'".($_POST['my_travels_places_type'] == $term->slug ? ' selected="selected"' : '').">".$term->name."</option>\n";                   
            endforeach;
            ?>
         </select>