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?

2
  • Where did you put that 404-test? Commented Jul 1, 2017 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; } } Commented Jul 1, 2017 at 11:41

1 Answer 1

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;
  }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.