Displaying only used categories in filter

Is it possible to hide categories from the listings search page filter where there are no listings with those categories yet? It is annoying to try to filter a category and find nothing until there is a listing added that uses it.

Nevermind, I figured it out:

For listings:

add_filter( 'hivepress/v1/forms/listing_filter', function( $form ) {
    $categories = $form[ 'fields' ][ '_category' ][ 'options' ];
    foreach ( $categories as $term_id => $category ) {
        if ( $term_id == 0 ) {
            continue;
        }
        $term = get_term( $term_id, 'hp_listing_category' );
        $count = $term->count;
        if ( $count == 0 ) {
            unset( $form[ 'fields' ][ '_category' ][ 'options' ][ $term_id ] );
        }
    }
    return $form;
}, 1000 );

And for vendors:

add_filter( 'hivepress/v1/forms/vendor_filter', function( $form ) {
    $categories = $form[ 'fields' ][ '_category' ][ 'options' ];
    foreach ( $categories as $term_id => $category ) {
        if ( $term_id == 0 ) {
            continue;
        }
        $args = [
            'post_type'      => 'hp_vendor',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'tax_query'      => [
                  'relation'     => 'AND',
                  [
                      'taxonomy'   => 'hp_vendor_category',
                      'field'      => 'id',
                      'terms'      => [ $term_id ]
                  ]
            ]
        ];
        $query = new WP_Query( $args );
        $count = (int)$query->post_count;
        wp_reset_postdata();

        if ( $count == 0 ) {
            unset( $form[ 'fields' ][ '_category' ][ 'options' ][ $term_id ] );
        }
    }
    return $form;
}, 1000 );
1 Like