Logged in and Logged out Body Classes

Today I wound up needing a logged-out body class on a WordPress site I’m building. Any individual who has ever coded a WordPress sites has probably included the body_class() capacity to their websites and it would look something like the following:

<body <?php body_class(); ?>>

Well, the body_class() function permits you to effectively include classes specifically into the function like the following:

<body <?php body_class('class-name');?> >

Obviously, using this logic it will add the “Logged-out” class to the body tag on every page/post/custom taxonomy page across my website. You can include other conditional functions to only show the the class name on certain types of pages such as if a post is in a certain category.

// Add specific CSS class by filter
add_filter('body_class','er_logged_in_filter');
function er_logged_in_filter($classes) {
if( is_user_logged_in() ) {
$classes[] = 'loggedin-product-class';
} else {
$classes[] = 'loggedout-product-class';
}
// return the $classes array
return $classes;
}

Sometimes we need to Call Different Body Classes. Like when we want to call a class only who are logged in user and who are visitor or not logged in. We can use the above code in functions.php in wordpress to execute the body classes.

2 thoughts on “Logged in and Logged out Body Classes”

  1. Hello ,

    In my local development environment, after having included the code ”
    <body >” in a snippet , I got this FATAL ERROR in my WORDPRESS.

    Fatal error: Uncaught Error: Call to a member function get() on null in C:\Users\mario\Local Sites\stagingwpsidraalfapt\app\public\wp-includes\post-template.php on line 788
    6 0.5330 14913432 do_action( ) ...\wp-settings.php:461
    7 0.5330 14913808 WP_Hook->do_action( ) ...\plugin.php:476
    8 0.5330 14913808 WP_Hook->apply_filters( ) ...\class-wp-hook.php:331
    9 0.7985 19373224 Code_Snippets\execute_active_snippets( ) ...\class-wp-hook.php:307
    10 0.8004 19421464 Code_Snippets\execute_snippet( ) ...\snippet-ops.php:544
    11 0.8004 19436984 eval( ' body_class('class-name');' ) ...\snippet-ops.php:484
    12 0.8004 19436984 body_class( ) ...\snippet-ops.php(484) : eval()'d code:1
    13 0.8005 19436984 get_body_class( ) ...\post-template.php:595

    Can you please help me to recover my local WORDPRESS environment.

    Thank You
    Mário Santos

    1. Thanks for your comment.
      well, i think you having conflict with another existing plugin.
      i am going to share a class, no need to use any snippet. only css

      Logged in stage:
      body.logged-in {
      }

      Logged out State:
      body:not(.logged-in) {
      }

      you can use those css which one you need.

      Thanks
      Md. Elias

Leave a Comment

Your email address will not be published. Required fields are marked *

0 Shares
Tweet
Share
Pin
Share