Support

Account

Home Forums Front-end Issues Hide empty categories

Solving

Hide empty categories

  • Hi all,

    So I have two custom post types, Media and Artist. Artists add each image or film as a new post (Media), there is a relationship field for each media post titled ‘Artist’, so when adding an image they select the associated artist.

    Another the artist will do is select a category for the media post. This is so that on the artist page when pulling in the artist content, there is an option to then filter based on the Media category.

    I can output the categories but the problem is, it shows all categories, regardless if the artist has content for a particular category or not. Is there any way to hide hidden categories and possible hide filters alltogether if there is only 1?

    Here is the code I am using to output the category filters:

    			<div class="filter-btn">	
    				<ul id="buttons">
    					<li class="active" data-target="artists">All Work</li>
    					<?php 
    					$categories = get_categories( array(
    						'taxonomy'  => 'media_category',
    						'orderby' => 'name',
    						'parent'  => 0,
    						'hide_empty' => true,
    					) );
    					foreach ( $categories as $category ) {
    						printf( '<li data-target="%2$s">%2$s</li>',
    							esc_url( get_category_link( $category->term_id ) ),
    							esc_html( $category->name )
    						);
    					}
    					?>
    				</ul>
    			</div> 	

    Any help would be fantastic.

    Thanks
    Lee

  • The problem in the OP is likely due to the fact that artists can share categories, so while one may not have anything in a category others might making them non empty.

    There isn’t really any way to do what you want to do directly.

    What you would need to do is get all of the media posts related to the artist then loop over all of them to get collect a list of categories and then use this in the “include” argument for getting the terms.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.