Search code examples
wordpressdrop-down-menucustom-post-type

How to get child categories from parent category of custom post type and display in dropdown?


Finally, I can get subcategories from a custom post-type category and everything works fine. The problem is when I want to get the same but with a dropdown for responsive. Is possible? I need to hide empty terms too. thanks!

here the code:

<ul>
<?php $tax = get_term_by('slug', 'cursos', 'portfolio_category');
$tax_id = $tax->term_id;
$args = array(
'child_of'   => $tax_id,
'taxonomy' => 'portfolio_category',
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 0,     
'title_li' => '',
'hide_title_if_empty' => 0
);
wp_list_categories($args); ?></ul>

Solution

  • You can use get_categories to get portfolio_category. Try the below code.

    <ul class="show_on_desktop">
        <?php 
            $tax    = get_term_by('slug', 'cursos', 'portfolio_category');
            $tax_id = $tax->term_id;
    
            $args = array(
                'child_of'     => $tax_id,
                'taxonomy'     => 'portfolio_category',
                'orderby'      => 'name',
                'show_count'   => 0,
                'pad_counts'   => 0,
                'hierarchical' => 0,     
                'title_li'     => '',
                'hide_empty'   => true
            );
            wp_list_categories($args); 
        ?>
    </ul>
    
    <?php 
        $cats = get_categories( array( 
            'child_of'   => $tax_id,
            'taxonomy'   => 'portfolio_category',
            'hide_empty' => true
        ) ); 
    ?>
    <select class="show_on_mobile">
        <?php foreach ( $cats as $cat ) : ?>
            <option value="<?php echo get_term_link( $cat->term_id ); ?>"><?php echo $cat->name; ?></option>
        <?php endforeach; ?>
    </select>