Categories
Web Development WordPress

Adding User-Specific Content to a WordPress page

There are many ways to go about this but in this post I will be focusing on using php in your WordPress page template to add content that can only be seen by users who are logged into administrator accounts.

Let’s say we have a secret message for administrators “The prize is behind door number 2”. We don’t want to share this invaluable, secret message with just anyone, we only want our friends who have administrator accounts on our website to be able to see the message.

We can create this functionality easily with WordPress using some of it’s many defined PHP functions. All we have to do are the three lines of code below:

if ( is_admin() ) {
     echo 'The prize is behind door number 2';
}

We can also use this same method with a different function to require the user to be logged in to see the message:

if ( is_user_logged_in() ) {
     echo 'The prize is behind door number 2';
}

We can even use this technique to show the message to a specific user and no one else, for a personalized message or something using the code below:

if ( '3' == get_current_user_id() ) {
     echo 'The prize is behind door number 2.';
}

I hope these three short examples demonstrate to you how powerful WordPress custom code using the pre-defined functions can be. Using a relatively small amount of code, I can extend this functionality to add some really useful new features to my website and so can you. Happy WordPressing!

Leave a Reply