• I’m using the code below as suggested in the codex to add the category names as a body-class for each post/page. However, the search results page also picks up on these body classes — e.g. if you search for something and it retrieves results from posts in the about-us category, the about-us body class is added to the search results page.

    I’d like to find a way to exclude the search results page from this function, but I don’t know how to go about it.

    // add category nicenames in body and post class
    
    function category_id_class( $classes ) {
        global $post;
        foreach ( get_the_category( $post->ID ) as $category ) {
            $classes[] = $category->category_nicename;
        }
        return $classes;
    }
    add_filter( 'post_class', 'category_id_class' );
    add_filter( 'body_class', 'category_id_class' );
Viewing 1 replies (of 1 total)
  • Thread Starter raquelxmoss

    (@raquelxmoss)

    Never mind! I figured it out. I did the following:

    // add category nicenames in body and post class, allows different colours (via css) for each category
    function category_id_class( $classes ) {
        if ( is_search() ) {
              $classes[] = 'search-results-page';
              return $classes;
          }
    
        else
    
        global $post;
        foreach ( get_the_category( $post->ID ) as $category ) {
            $classes[] = $category->category_nicename;
        }
        return $classes;
    }
    add_filter( 'post_class', 'category_id_class' );
    add_filter( 'body_class', 'category_id_class' );
Viewing 1 replies (of 1 total)
  • The topic ‘Excluding the search results page from body class function’ is closed to new replies.