简体   繁体   中英

Show children of custom taxonomy terms

I have the WP Jb manager plugin which I believe is just a custom post type for jobs. I have enabled categories created some categories.

I need to just show the children of each category instead of the whole list of categories.

I have the following code:

<?php
$terms = get_terms( 'job_listing_category', 'orderby=count&hide_empty=0' );
$count = count($terms);
if ( $count > 0 ){
 echo "<ul>";
 foreach ( $terms as $term ) {
   echo "<li>" . $term->name . "</li>";

 }
 echo "</ul>";
}
?>

Which outputs a list of all categories (parent and children) as so:

  • Office
  • Warehouse
  • Manufacturing
  • Industrial
  • Construction
  • Building Services Engineers

The parent categories are the bold ones: Office, Industrial and Construction. I want to take one of them and display the children of that category only.

For example: get_category('industrial', 'children_of') (I know that's not the correct syntax), so it would result in showing the children only of the industrial category:

  • Warehouse
  • Manufacturing

I can't seem to find a way to do this - Could anyone help?

I managed to do this by using the following code:

<?php
$terms = get_terms( 'job_listing_category', 'parent=59' );
$count = count($terms);
if ( $count > 0 ){
 echo "<ul>";
 foreach ( $terms as $term ) {
   echo "<li>" . $term->name . "</li>";

 }
 echo "</ul>";
}
?>

You can fetch the parent categories and then construct a list for each subcategory like so:

<?php
$taxonomies = get_terms(array(
    'taxonomy' => 'job_listing_category',
    'hide_empty' => false,
    'parent' => 0,
));

if (!empty($taxonomies)):
    foreach ($taxonomies as $parent) {
        $output = '<ul>';
        $children = get_terms(array(
            'taxonomy' => 'job_listing_category',
            'parent' => $parent->term_id,
            'hide_empty' => false,
        ));
        foreach ($children as $child) {
            $output .= '<li>' . esc_html($child->name) . '</li>';
        }
        $output = '</ul>';
    }
    echo $output;
endif;

Note that the code wasnt tested. Find more info here: https://developer.wordpress.org/reference/functions/get_terms/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM