0

I'm trying to add a custom body class to WordPress which should be the author of the post which is displayed. I looked at different how to's and tried to create some code but it doesn't work:

add_filter( 'body_class' , 'ft_add_guest_body_class' );

function ft_add_guest_body_class( $classes ) {

    // add 'wp_admin' to the $classes array

    if (get_the_author() != 'MrX')
        $classes[] = 'wp_admin';

    // return the $classes array
    return $classes;

}

The problem is that the wp_admin body class is displayed on every page and post. When I remove the conditional the body class is still applied so it must be that.

5
  • Do some debugging then. What does get_the_author() return?
    – Pekka
    Jan 20, 2012 at 11:26
  • it actually returns nothing...
    – Thomas
    Jan 20, 2012 at 13:12
  • that's your problem then. I think this is because the post hasn't been loaded yet. Not sure what the best is to deal with this... I'll flag this for migration to Wordpress.SE, the guys there will know
    – Pekka
    Jan 20, 2012 at 14:11
  • Beware the PHP voodoo.
    – Raphael
    Jan 20, 2012 at 17:40
  • Did anyone get a working version of this?
    – Pete
    Jul 27, 2019 at 6:37

2 Answers 2

1
$author = $wp_query->post->post_author;
$author = get_user_by('id', $author);
author->user_nicename;

That should get you the author slug which you can use in your conditional statement. get_the_author can only be used inside the loop.

0

It's because you're trying to use get_the_author() outside of the Loop. Try using $post->post_author instead, which will return the author's ID for the current post.

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.