Support » Developing with WordPress » Need some insight into function / filter that is not working

  • Resolved Jack

    (@moxie)


    Something is wrong with underneath code I think, because after updating to PHP 7.4 from 5.6 it is not working anymore and puts the site offline (server error). The code was put inside the functions file of the Masonic theme. I now moved it to a code snippet using the Code Snippet plugin, but with the same result. Removing this code in either place fixes things.

    add_filter('body_class','add_category_to_single');
      function add_category_to_single($classes) {
        if (is_single() || is_category() || in_category() ) {
          global $post;
          foreach((get_the_category($post->ID)) as $category) {
            // add category slug to the $classes array
            $classes[] = $category->category_nicename;
          }
        }
        // return the $classes array
        return $classes;
      }
Viewing 3 replies - 1 through 3 (of 3 total)
  • Nothing obvious jumps out at me, except that you aren’t using a prefix on your function name (in case of having a function already named that).
    You can turn on DEBUG and see what the error log says. https://wordpress.org/support/article/editing-wp-config-php/#wp_debug

    Moderator bcworkz

    (@bcworkz)

    in_category() requires a term parameter be passed. For category archive requests, when the body_class filter fires, the current post may not be defined because the loop hasn’t started yet. In some cases the global $post might be set to the first post returned, but it shouldn’t be relied upon to be so. In any case, the first post’s categories may not represent any other posts on the page. The code assigning term name classes is really meant for a single post request, not a category archive.

    Thread Starter Jack

    (@moxie)

    Thanks for all the suggestions, I think it has to do with the in_category.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Need some insight into function / filter that is not working’ is closed to new replies.