問題描述

我需要説明當前我正在查看的自定義分類存檔頁面是否有子類別。我有一個情況,有很多自定義類別與孩子,網站只顯示在行尾的帖子。否則,它應該顯示一個到下一步的類別的鏈接。我找到了這個代碼段,但它似乎不適用於自定義分類法。

function category_has_children() {
global $wpdb;   
$term = get_queried_object();
$category_children_check = $wpdb->get_results(" SELECT * FROM wp_term_taxonomy WHERE parent = '$term->term_id' ");
    if ($category_children_check) {
        return true;
    } else {
       return false;
    }
}   

<?php
    if (!category_has_children()) {
        //use whatever loop or template part here to show the posts at the end of the line
   get_template_part('loop', 'index'); 
       }   

    else {
       // show your category index page here
    }
?>

最佳解決方案

這可能是也可能不是更好的方法,但是我將如何做到這一點:

$term = get_queried_object();

$children = get_terms( $term->taxonomy, array(
'parent'    => $term->term_id,
'hide_empty' => false
) );
// print_r($children); // uncomment to examine for debugging
if($children) { // get_terms will return false if tax does not exist or term wasn't found.
    // term has children
}

如果當前分類術語有孩子,get_terms 函數將返回一個數組,否則返回 false

測試和工作在我的本地香草安裝與 Custom Post Type UI 插件用於 CPT 生成。

次佳解決方案

通過 get_term_children 也有通用的 WP 可能性。

<?php
$children = get_term_children($termId, $taxonomyName);

if( empty( $children ) ) {
    //do something here
}

參考文獻

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