Discover in this tutorial how to hide the content of any block from users who have not purchased an Easy Digital Downloads product, using code.
Depending on the website you have and your strategy, there are times when you may want to display different content depending on whether the user is logged in or not.
In today’s tutorial you are going to see how to control that the content of a block is only displayed to customers who have purchased a certain product (or subscription), combining the pre_render_block
filter and the conditional edd_has_user_purchased
.
Let’s see how:
Steps to hide the content of a block to customers who have not purchased a given product
1. Choose the block you want to hide
First, choose the block whose content you want to be visible only to users who are logged in with their account.
If you want this to apply to more than one set of blocks, you can choose the group block as the container.
2. Add a custom CSS class
Once you have created the block, go to the “Advanced” section and add hide-not-customer
in the block’s “Additional CSS class(es)”.
3. Modify the access to the block content
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
In this code you use the pre_render_block
filter, which allows you to access the attributes of all blocks, along with the conditional edd_has_user_purchased
.
In it you indicate that if the user has not purchased a product from Easy Digital Downloads (in this case the one with the identifier 55) and the block has the CSS class hide-not-customer
, they will not be able to see the content of the block. Instead, if they have purchased that product it will show them the entire block, just as you created it.
If you want this to apply to more than one product you can pass an array with the identifiers of all the products.
In the example you order to display an empty message so that the user that is not a customer does not see anything, but if you prefer to show a text indicating that, to see the content, you must access your account on the web, you can modify it by the following:
$message ='To view the content you must have acquired...';
However, keep in mind that since you are using a PHP filter you have the limitation that you will only see the result in the web frontend, in the backend the changes will not be reflected.
If you want to make it even easier for your client you can create a block variation so that they can choose the block directly from the user interface. You can take a look at this tutorial where I explained it for Restrict Content Pro.
Conclusions
Now you know how to make any block visible only to users who have purchased an Easy Digital Downloads product on your website.
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉