WordPress: Get Last Child Term from Custom Taxonomy
To get only the last child term from a custom taxonomy of the current post type in WordPress, you can use the following code:
// Get the current post type
$current_post_type = get_post_type();
// Get the terms of the custom taxonomy for the current post type
$terms = get_terms(array(
'taxonomy' => 'your_custom_taxonomy',
'object_ids' => get_the_ID(),
'hide_empty' => false,
));
// Check if there are any terms
if (!empty($terms)) {
// Get the last child term
$last_child_term = end($terms);
// Loop through the terms to find the last child term
foreach ($terms as $term) {
if ($term->parent != 0 && !term_exists($term->parent, 'your_custom_taxonomy')) {
$last_child_term = $term;
break;
}
}
// Output the last child term
echo $last_child_term->name;
}
Make sure to replace 'your_custom_taxonomy' with the slug of your custom taxonomy. This code will retrieve all terms of the custom taxonomy associated with the current post type and then find the last child term by checking the parent IDs. Finally, it will output the name of the last child term.
原文地址: https://www.cveoy.top/t/topic/qjcD 著作权归作者所有。请勿转载和采集!