CreatiqueMedia Blog

CM-Post-0009-20221104-Hide-Show-Using-WordPress-Body-Classes

Hide and Show Content Using Conditional Logic Using WordPress and Elementor Pro!

Index

1 – Description
2 – What We’re Building!
3 – PHP Code
4 – Add Code To Functions.php File (Contains Affiliate Link)
5 – CSS
6 – Quick Quiz
7 – Links
8 – Conclusion

1 - Description

HOLY MOLY this is COOL!!

Okay, so I am working on my own “support” site for clients to login to,  so they can send support requests and/or make a payment. I want logged in users to see one thing and logged off users to see another.

To do this, we MUST have the following:

So, when using Elementor Pro, there are some limitations. For instance, Elementor doesn’t incorporate Conditional Logic in their product. Meaning, you want to hide some content from people that are not logged into your site, or hide content from people that are logged in.

I used to have to use a PAID for plugin for this with my WordPress website builds, but now I can simply use a WordPress Child Theme like Astra Pro.

Then, that gives me access to the functions.php file that I can use to add custom PHP code to, to add more functionality to my WordPress website!

A WordPress Body_Class, by default, auto-generates several classes, such as the following: 

				
					.rtl {}
.home {}
.blog {}
.archive {}
.date {}
.search {}
.paged {}
.attachment {}
.error404 {}
.single postid-(id) {}
.attachmentid-(id) {}
.attachment-(mime-type) {}
.author {}
.author-(user_nicename) {}
.category {}
.category-(slug) {}
.tag {}
.tag-(slug) {}
.page-parent {}
.page-child parent-pageid-(id) {}
.page-template page-template-(template file name) {}
.search-results {}
.search-no-results {}
.logged-in {}
.paged-(page number) {}
.single-paged-(page number) {}
.page-paged-(page number) {}
.category-paged-(page number) {}
.tag-paged-(page number) {}
.date-paged-(page number) {}
.author-paged-(page number) {}
.search-paged-(page number) {}

				
			

However, we can also create our own custom classes.

Because of this, we can determine what can be seen and not seen!

So, if I want to hide content from users that are logged in as well as hide content from users that are NOT logged in, I just add some PHP code to my child theme’s functions.php file to create additional classes to be added to the WordPress “body_class” element.

 

What I won’t be covering in this tutorial due to this being a bit more higher level and plus there are tons and tons of YouTube and blog articles covering the aforementioned, just Google it: 

  • Installing WordPress
  • Getting a paid license and installing Elementor Pro
  • Getting a paid license and installing the Astra Pro child theme

That’s what we will be focusing on today, so let’s get started y’all!

2 - What We're Building!

Today, what we are going to build is a way to show content to users that are logged into your website while hiding content meant for logged off users and vice versa.

 

So, here is what it will look like once we are done:

 

View For Logged In Users

View For Logged Off Users

3 - PHP Code

The PHP code we will be using is the following:

				
					/**
* CreatiqueMedia Functions 
*/
// Add CSS class for logged in and logged out users
add_filter('body_class','cm_logged_in_filter');
function cm_logged_in_filter($classes) {
if( is_user_logged_in() ) {
$classes[] = 'cm-logged-in';
} else {
$classes[] = 'cm-logged-out';
}
// return the $classes array
return $classes;
}

				
			

Now, you can probably tell what this does, for the most part!

So, let me break this down!

The “add_filter” function is a built-in, default WordPress filter hook function used to help us Developers to make changes to the default WordPress structure and layout.

Therefore, when we use the following PHP code:

  • Add_filter(‘body_class’, ‘cm_logged_in_filter’)

What we are telling WordPress to do is to create a filter that we will call on called “cm_logged_in_filter”. This can be any name you want, but I always use “cm” as a prefix for CreatiqueMedia so I know I was the one that created this customization, plus, they should always be unique so they don’t conflict with something else using a similar name.

So, the “add_filter” function is looking to use the ‘body_class’ and add whatever classes we create! using the following code:

So, I have my custom unique function “cm_logged_in_filter”, then I tell WordPress to use the “$classes” parameter variable that are within the parenthesis. After that, within the function block, I use conditional logic to determine if a user is logged in or not using an “if” statement.

The code that will do this is:

  • if( is_user_logged_in() )

Instead of writing my own helper function to determine if a user is logged into WordPress, I can simply just use the already built-in, default helper function called “is_user_logged_in()”. This makes customizations to WordPress so much easier and less cumbersome!

So, the “if” block is:

  • if( is_user_logged_in() ) {

$classes[] = ‘logged-in-condition’;

}

After the “if” statement, I use the “$classes” variable again, but this time, I put brackets after it like so:

  • $classes[]

What this does is it turns the variable of “$classes” into an array so we can add multiple items to it. For instance, if we just needed or wanted to add one class only, we wouldn’t need to use the array brackets ([]) at all, but since we have two classes we want to add, then we use the array brackets. Of course, you can still use the brackets even with one class, but the point is, that for multiple items, you need the brackets, so most Devs will just stick with the array method, even for one class to avoid human errror down the road.

Okay, to better understand what the “if” statement is doing, let’s imagine a two-way conversation between WordPress and our PHP code:

PHP: Hey, WordPress!

WordPress: Yo, PHP, what’s up bro?

PHP: Hey, not much man! I just have this annoying Dev here that wants me to ask you some questions!

WordPress: Ahh crap man, I hope this isn’t about what happened between me and Ruby?

PHP: What? You and Ruby? No way! I thought you and Swift were a thing?

WordPress: Dude, you didn’t hear?

PHP: Hear? Hear, what man?

WordPress: Swift totally dumped me for JavaScript!

PHP: Damn that JavaScript! He is such a STUD! I remember back in the day when I was always sought after, but here we are now with this punk, JavaScript screwing it up for the rest of OGs.

WordPress: NO KIDDING BRO! We should definitely get with Drupal and Joomla and whoop JavaScript’s @$$! HEY! Wait a minute, you’re only a year older than JS dude!

PHP: First of all, DUDE! Drupal can’t beat his way out of a wet paper sack and Joomla hides in his bedroom all day playing MineCraft! And, SECOND! In “Programming Years”, one year is like a thousand years, bro!

WordPress: Yeah, you gotta point! Well, I hear this new fella named “React” is like a Brazilian Jiu Jitsu badass, maybe he can help us?

PHP: NICE! Hold on! Wait, wait, but first, this Dev dude won’t leave me alone until this is done! Okay, this should be easy for you! All you have to do is use your “is_user_logged_in” helper function to determine if someone is logged in. If they are, then just add our custom class “cm-logged-in-condition” class to your “body_class” element when WordPress loads! However, if someone is logged off, then you add the “cm-logged-off-condition” class to your “body_class” when WordPress loads! Now don’t screw this up because this Dev dude keeps Googlin’ PHP free CMS’s man! I must be getting too old for these young whipper snapper Devs. They don’t even teach me anymore at these damn schools, bunch of Marxists!

WordPress: Hey dude, it’s hurting all of us old timers man! And no sweat bro, I’m on this! BTW. we still meeting up at Linux’s pad tonight for poker with C++, PERL, and COBOL?
PHP: They rescheduled due to C++ visiting grandkids, PERL broke her hip, and COBOL is in rehab for his life falling apart and no one needing him anymore!
WordPress: FML!

4 - Add Code To Functions.PHP File

To add this code to your functions.php file, you’ll either need access to your webhost’s file manager to add the code, or you’ll need an FTP client to remotely login to your website! I use both methods, but for this project, I will just use my webhost’s file manager in my customer dashboard since we are just adding a snippet of code.


Which is a great segway for this commercial using my affiliate link – YAY!

I know you “Advertisement Junkies” out there just love these fantastic lil commercials I put together on blog posts, so here you go:

Affiliate Links Ahead 👉🏻 SiteGround Web Hosting Service

Did someone say link!?

Why sure!

I got that right here, somewhere!

Now, where did I put that sucker?

Ahh, here it is!

I was sitting on it, AGAIN!

Now where were?

Ahh, yes!

How to add code to the functions.php file!

Okay, now that your viewing pleasure has been satisfied, let’s move onto accessing the functions.php file.

Open up your web host’s website and login to your account. Again, since I use SiteGround, I will login to that account.

After logging into my account, I click on Websites at the top:

Then, I navigate to the website I want to manage, but if you only have one, then finding it makes it easier!

After you find your website, click on the Site Tools button:

You will then be taken to your website’s dashboard. Then, just navigate to, Site > File Manager:

This will provide a right pane view of all your WordPress and website files:

You will see in this list that I have several website folders!


My main website is in the CreatiqueMedia.com folder and then I have 3 sub domains of my main site, which are:


The folder I want is the Support.CreatiqueMedia.com sub domain:

Once we’re in the folder, we need to navigate to the following: public_html > wp-content > themes > creatiquemedia-child > functions.php:

As you can see from the screenshot above, I pasted the PHP code in. Now, I save the file and I go back to my website.

 

This now takes us to our next section…

5 - CSS

WARNING!

It’s BEST to add ALL your custom CSS to one central location so you know where all your CSS code is. Keeping custom CSS code in different places throughout your WordPress website will make it harder to determine an issue down the road if one should arise!


I ALWAYS add my custom CSS either to the WordPress customizer, or use the Elementor Pro’s custom CSS editor under Site Settings > Custom CSS.

I open up Elementor Pro and I navigate to the hamburger menu in the upper left corner:

Then, I navigate to “Custom CSS” and I paste the following code in the editor:

				
					/* Conditional Logic */
/* Hide Logged-In and Logged-Out Content */
.cm-logged-in-condition .cm-hide-logged-in {
	display: none!important;
}
.cm-logged-out-condition .cm-hide-logged-out {
	display: none!important;
}

				
			

What this code does is if a user is logged in to your website, the “cm-hide-logged-in” class is added, or if a user is not logged in to your website, then the “cm-hide-logged-out” class is added.

Because of this, we can hide and show content using CSS!

Now, whichever element or element section I add the additional classes (.cm-hide-logged-in and .cm-hide-logged-out) to will either show or hide depending on the conditions that are met. Those conditions are the classes we created using our custom PHP code which is .cm-logged-in-condition and .cm-logged-out-condition. When a user is logged in, the .cm-logged-in-condition class is created.

Then, when we add the “.cm-hide-logged-in” class to an Elementor element or section, that content will NOT display and vice versa for the “.logged-out-condition”!

Isn’t that COOL?!

You don’t have to use a PAID plugin anymore!

6 - Quick Quiz

Quiz Question 1
Quiz Question 2
Quiz Question 3

7 - Links

Project Links
Social Links

8 - Conclusion

Well, that’s it folks!

If you have any web development need, then connect with us and let us know how we can help you!

Until next time, thanks for tuning in on the CreatiqueMedia and Ron The Web Dev blog!

 

We appreciate your readership and will keep trying to post educational material for your web dev craving to thrive on!

If you are interested in having a website, web app, or anything built related to web development for your business or personal need, please contact us today at:

OR

Call us at: 405-831-3048

Remember to keep DEV’N!

8 thoughts on “CM-Post-0009-20221104-Hide-Show-Using-WordPress-Body-Classes”

  1. I wanted to express my gratitude for this well-written and insightful post. It’s evident that you’ve gone above and beyond to deliver valuable information. Thank you for enriching our understanding with your work!

  2. Your post is incredibly helpful! It answered all the questions I had and provided additional insights. I’m grateful for the effort you’ve put into sharing this valuable information.

Leave a Comment

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