Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.