Subcategory Links at the Top of Category Archives
Shows a row of links to the child categories at the top of a category archive, helping visitors drill down into large sections.
Opens WPIDE on
Code
add_action( 'loop_start', function ( $query ) {
static $done = false;
if ( $done || ! $query->is_main_query() || ! is_category() || is_paged() ) {
return;
}
$done = true;
$children = get_categories( array(
'parent' => get_queried_object_id(),
'hide_empty' => true,
) );
if ( ! $children ) {
return;
}
echo '<nav class="wpide-subcategories" aria-label="Subcategories"><ul style="list-style:none;margin:0 0 2em;padding:0;display:flex;flex-wrap:wrap;gap:.5em;">';
foreach ( $children as $child ) {
echo '<li><a href="' . esc_url( get_category_link( $child ) ) . '" style="display:inline-block;padding:.3em .8em;border:1px solid currentColor;border-radius:999px;text-decoration:none;">' . esc_html( $child->name ) . ' <span style="opacity:.6;">' . esc_html( number_format_i18n( $child->count ) ) . '</span></a></li>';
}
echo '</ul></nav>';
} );
Notes
Only categories with posts are listed. The position depends on where your theme starts the post loop.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.