• Resolved inula

    (@janetb)


    I would like to put category class in single post. I searched the forum and found this:

    add_filter('body_class','add_category_to_single');
    function add_category_to_single($classes, $class) {
    	if (is_single() ) {
    		global $post;
    		foreach((get_the_category($post->ID)) as $category) {
    			echo $category->cat_name . ' ';
    			// add category slug to the $classes array
    			$classes[] = 'category-'.$category->slug;
    		}
    	}
    	// return the $classes array
    	return $classes;
    }

    When I put this in functions.php I get error:
    ‘ArgumentCountError thrown
    Too few arguments to function add_category_to_single(), 1 passed in /home/vcsleen/domains/vcsleen.nl/public_html/wp-includes/class-wp-hook.php on line 288 and exactly 2 expected’

    What am I doing wrong???

    In same functions.php I use this:

    // category id in body and post class
    function category_id_class($classes) {
    	global $post;
    	foreach((get_the_category($post->ID)) as $category)
    		$classes [] = 'cat-' . $category->cat_ID . '-id';
    		return $classes;
    }
    add_filter('post_class', 'category_id_class');
    add_filter('body_class', 'category_id_class');

    Maybe that causes the error?

    • This topic was modified 5 years, 4 months ago by inula.
Viewing 4 replies - 1 through 4 (of 4 total)
  • instead of function add_category_to_single($classes, $class) {
    use function add_category_to_single($classes) {

    also, what is the purpose if this line (maybe other than testing):
    echo $category->cat_name . ' ';
    it is not needed to generate the additional CSS classes – consider to remove it

    Theme Author Tom

    (@edge22)

    Thanks, Michael! This should be the final function:

    add_filter( 'body_class', function( $classes ) {
        if ( is_single() ) {
            global $post;
    
            foreach( ( get_the_category( $post->ID ) ) as $category ) {
                $classes[] = 'category-' . $category->slug;
            }
        }
    
        return $classes;
    } );
    Thread Starter inula

    (@janetb)

    Thanks again, Tom!

    Theme Author Tom

    (@edge22)

    No problem ??

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘category class in single’ is closed to new replies.