Category Loop

Posted on Oct 22, 2024

by Jimmy

Last updated on February 13, 2025


Simple way to list all existing categories and adding an active class on the active category.

PHP
        
            <?php $categories = get_categories(); ?>
<a href="<?= get_permalink( get_option( 'page_for_posts' ) ); ?>" class="category__item<?php is_home() ? print ' category__item--is-active' : ''; ?>">All</a>
<?php foreach( $categories as $category ) : ?>
    <a class="category__item<?php if( $cat == $category->cat_ID ) : ?> category__item--is-active<?php endif; ?>" href="<?php "". print home_url() . "/category/" . $category->slug . "/" ?>"><?php print $category->cat_name; ?></a>
<?php endforeach; ?>        
    

Back to Snippets