0

I'm using this function to retrieve body and single post classes from their slugs.

add_filter( 'post_class', 'fl_pages_bodyclass' );
add_filter('body_class','fl_pages_bodyclass');
function fl_pages_bodyclass($classes) {
    if (is_page() || is_single() ) {
        // get page slug
        global $post;
        $slug = get_post( $post )->post_name;

        // add slug to $classes array
        $classes[] = $slug;
        // return the $classes array
        return $classes;
    } else { 
        return $classes;
    }
} 

This function is working fine, but I would like to include posts inside loops. I've tried removing if(is_ ..). Then it is working, but a problem arises on a 404 page - I got “Trying to get property of non-object in” error - so I've tried to exclude 404 page by

if (is_404() ) {
     return $classes;
     } 

But it doesn't work. What am I doing wrong? Or how can I include posts in loops?

  • Where did you put that 404-test? – cjbj Jul 1 '17 at 10:15
  • add_filter( 'post_class', 'fl_pages_bodyclass' ); add_filter('body_class','fl_pages_bodyclass'); function fl_pages_bodyclass($classes) { // get page slug global $post; $slug = get_post( $post )->post_name; // add slug to $classes array $classes[] = $slug; // return the $classes array return $classes; if (is_404() ) { return $classes; } } – Gore Jul 1 '17 at 11:41
1

The error you get is produced by $slug = get_post( $post )->post_name; because there is no post_name on a 404 page. So, to prevent this error you must structure the function in a way it doesn't get to this line when it is called on a 404-page. Like this:

add_filter ('post_class', 'fl_pages_bodyclass');
add_filter ('body_class', 'fl_pages_bodyclass');
function fl_pages_bodyclass ($classes) { 
  global $post;
  if (!is_404()) {
    $slug = get_post($post)->post_name; 
    $classes[] = $slug;
    }
  return $classes;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.