問題描述

我在管理員中創建一個年齡選擇菜單,由 age 的分類組成。分類法分層如下:

  • 18-25 歲 (父母,身份證號 183)

    • 18(小孩)

    • 19

    • 20

    • 21

    • 22

    • 23

    • 24

    • 25

  • 26-30(父母,184 號)

    • 26

    • 27

    • 28

    • 29

    • 三十

我只想列出孩子 (18,19 等等),而不是父母 (18-25,26-30) 等。目前我正在使用 get_termsparent 參數,但它不接受超過 1 個父 ID 。這是我到目前為止,這顯示了 18-25 歲的孩子。

    $ages = get_terms( 'age', array(
        'hide_empty' => 0,
        'parent' => '183',
    ));

這是我想要的,但不支持。我也嘗試過一個數組,但它也不工作。

    $ages = get_terms( 'age', array(
        'hide_empty' => 0,
        'parent' => '183,184',
    ));

我看到有一個 get_term_children 函數,但我不確定如何使用它,因為它看起來像只接受一個值。例如:在這個例子中,它將構建一個無序的列表,但是我可以修改選擇菜單。

<?php
    $termID = 183;
    $taxonomyName = "age";
    $termchildren = get_term_children( $termID, $taxonomyName );

    echo '<ul>';
    foreach ($termchildren as $child) {
    $term = get_term_by( 'id', $child, $taxonomyName );
    echo '<li><a href="http://'%20.%20get_term_link(%20$term->name,%20$taxonomyName%20)%20.%20'">' . $term->name . '</a></li>';
    }
    echo '</ul>';
?>

最佳解決方案

這應該適合你:

$taxonomyName = "age";
//This gets top layer terms only.  This is done by setting parent to 0.
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );
echo '<ul>';
foreach ( $parent_terms as $pterm ) {
    //Get the Child terms
    $terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
    foreach ( $terms as $term ) {
        echo '<li><a href="http://'%20.%20get_term_link(%20$term%20)%20.%20'">' . $term->name . '</a></li>';
    }
}
echo '</ul>';

次佳解決方案

你也可以做:

$terms = get_terms($taxonomyName);
foreach($terms as $term) {
    if ($term->parent != 0) { // avoid parent categories
        //your instructions here
    }
}

我注意到父母的”parent” 字段等於 0,一個小孩在其中有父 ID 。

第三種解決方案

我們可以通過使用 terms_clauses 篩選器在執行之前對 SQL 查詢進行過濾來排除頂級父級。這樣我們不需要在最終的 foreach 循環中跳過父母,因為它們不在返回的術語數組中,這樣可以節省我們不必要的工作和編碼

您可以嘗試以下操作:

add_filter( 'terms_clauses', function (  $pieces, $taxonomies, $args )
{
    // Check if our custom arguments is set and set to 1, if not bail
    if (    !isset( $args['wpse_exclude_top'] )
         || 1 !== $args['wpse_exclude_top']
    )
        return $pieces;

    // Everything checks out, lets remove parents
    $pieces['where'] .= ' AND tt.parent > 0';

    return $pieces;
}, 10, 3 );

要排除頂級父母,我們現在可以通過我們的參數數組來傳遞'wpse_exclude_top' => 1 。上面的過濾器支持新的 wpse_exclude_top 參數

$terms = get_terms( 'category', ['wpse_exclude_top' => 1] );
if (    $terms
     && !is_wp_error( $terms )
) {
    echo '<ul>';
        foreach ($terms as $term) {
            echo '<li><a href="http://'%20.%20get_term_link(%20$term%20)%20.%20'">' . $term->name . '</a></li>';
        }
    echo '</ul>';
}

只是一個説明,get_term_link()不接受術語名稱,只有,slug,ID 或完整的術語對象。對於性能,如果術語對象可用 (如這種情況),始終始終將術語對象傳遞給 get_term_link()

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。