简体   繁体   中英

Custom post type with taxonomy children

Through landing we are showing categories. Clicking on any category show child sub categories. But this shows child of child as well. following is our code to retrieve sub categories.

$terms = get_terms( 'msproduct' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    echo '<ul>';
    foreach ( $terms as $term ) {
        echo '<li>' . $term->name . '</li>';
    }
    echo '</ul>';
}

please advice. My category structure is following

Commercial Ovan
- 900 Series
-- Product 1
-- Product 2
- 700 Series
-- Product 1
- 600 Series
-- Product 1
-- Product 2
-- Product 3
-- Product 4

You might be able to use this. I'm not sure what your structure is, but assuming the page you're on is_tax() then checking against that conditional may work.

$taxonomy = "msproduct";
$args = (is_tax()) ? array() : array('parent' => 0); // don't show children if you're on a taxonomy page
$terms = get_terms( $taxonomy, $args );

if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    echo '<ul>';
    foreach ( $terms as $term ) {
        echo '<li>' . $term->name . '</li>';
    }
    echo '</ul>';
}

Reference:

https://developer.wordpress.org/reference/functions/get_terms/ https://codex.wordpress.org/Function_Reference/is_tax

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