Tutorial – Add a User Agreement Message to your WordPress

This will allow you to require your visitors to accept your User Agreement Terms with this little bit of code. This is great if you want to put a disclaimer, copyright notice, age required notice, or even adult content warning. The code is fairly simple and easy to implement, you will be adding it to your loop file(s) in your theme. Instead of showing you the code in one snippet I will be breaking it up into two because there is a part that goes at the top of the loop and the other part will go at the bottom.

Put this at the very top of your loop file(s)


	

You don't have Access to this content.

You must click the I Agree button to view this content.

Put this at the very bottom of your loop file(s)

Here is what a very basic loop.php file would look like with the added code.


	

You don't have Access to this content.

You must click the I Agree button to view this content.

Now that you have both parts that will be needed lets break it down a little bit further.


This part of the code is doing two things, first it is telling server to start a session which essentially means it allows your code to use and check for temporarily set cookies. These cookies will only stay on your computer until you close the browser you're using. This is great for making sure the person who clicked accept is the one viewing your website since once they close the window the cookie will disappear.

The second part is checking if the cookie grant_access has not been set, if it hasn't then we say it has a value of unset. We need to do this because by default cookies aren't set until the page is reloaded. On to the next part of the code:

if(isset($_POST['agree'])) {
	$_SESSION['grant_access'] = 'set';
}

This is a checking to see if the button "I agree" has been pressed and in turn posted its value. Once the button has been pressed/posted it changes the value of the temp cookie grant_access to set instead of unset. Now onto the third check:

if($_SESSION['grant_access'] == 'unset') {
?>
	

You don't have Access to this content.

You must click the I Agree button to view this content.

This part of the code is checking to see if the temp cookie grant_access value is unset. Remember the default value is unset as we defined it above. If it is then it spits out the little bit of HTML. If it value isn't unset it will show the content as normal. Now for the last bit of the code:

This is simply closing the else statement around the code that makes loop function once the user has clicked the I Agree button.

Note: If a user doesn't have cookies enabled for whatever reason then this message will reappear on every page/post they try to visit as the temporary cookie being set isn't saving due to cookies being disabled.

Leave a Reply