phpwordpress

How Can I Display Only Parent Categories on Wordpress?


I'm working with this directory site theme and in the search function, it has the "Search by: Category" option.

I'd like to rename that to "Search by: Location" and when people click the drop-down, it should only display the parent categories, which are the location names. It should not show any of the sub-categories.

here's the code...

        <div class="col-lg-4">
        <div class="dropdown dropdown-category">
            <select name="dropdown_category4" class="btn btn-secondary dropdown-toggle" type="button" id="listing_category">
                <option value="" selected><?php _e('Search by: Category', 'directorytheme'); ?></option>
                <?php
                $terms_links = get_terms('listing-categories');
                foreach( $terms_links as $terms_link ) : ?>
                    <option class="dropdown-item dropdown-cat" value="<?php echo "{$terms_link->slug}"; ?>"><?php echo "{$terms_link->name}"; ?></option>
                <?php endforeach; ?>
            </select>
            <?php if($listing_category != '') : ?>
                    <input type="hidden" name="s_listing_category" id="s_listing_category" value ="<?php echo $listing_category; ?>">
            <?php else : ?>
                    <input type="hidden" name="s_listing_category" id="s_listing_category">
            <?php endif; ?>
        </div><!--dropdown-->
    </div>

How can I modify it to do what I need it to do?

Thanks!


Solution

  • You can pass an array of parameters into get_terms.

    get_terms(array(
    'taxonomy' => 'listing-categories',
    'parent'   => 0
    ));
    

    parent 0 means top level terms.
    https://developer.wordpress.org/reference/functions/get_terms/