add body class if user is logged in

WordPress AI Code Robot

Create WordPress code snippets for free without a developer!

{Name (First):7.3} requested the  following code from my WordPress AI Code Generator.

add body class if user is logged in

The robot generated the following code:

Sure, here you go:

“`php
function nm_add_body_class($classes) {
if(is_user_logged_in()) {
$classes[] = 'logged-in';
}
return $classes;
}
add_filter('body_class', 'nm_add_body_class');
“`

In this piece of code, we're hooking into the `body_class` filter that WordPress provides. This filter allows you to add or manipulate the classes that are added to the `<body>` tag output in your theme.

Inside our function `nm_add_body_class()`, we use `is_user_logged_in()` WordPress function which returns true if the current visitor is logged in and false if not. If user is logged in, the 'logged-in' class is added to $classes array.

Finally, the modified data is returned and the function is linked to `body_class` filter using `add_filter()` function.

You can then use the 'logged-in' class in your theme's CSS to style the body when a user is logged in.

More
CODE SNIPPETS