WordPress Snippets at WPcustoms

Shorten category classes in post_class

Using post_class prints all category slug names the post belongs to. This may lead to a cluttered source. This WordPress snippet limits it to the first 5 category slugs.


/**
 * Snippet Name: Shorten category classes in post_class
 * Snippet URL: https://wpcustoms.net/snippets/shorten-category-classes-in-post_class/
 */
      function wpc_shorten_category_id_class($classes) {
        global $post;
        foreach((get_the_category($post->ID)) as $category)
            $classes[] = $category->category_nicename;
            return array_slice($classes, 0,5);
    }
    add_filter('post_class', 'wpc_shorten_category_id_class');