How to filter and restrict access to the content of a Gutenberg block in WordPress 5.7

Newest WordPress version 5.7 has brought some new filters to do some cool stuff with Gutenberg blocks with less code and more simplicity.

I’ve decided to try out simple two scenarios that I could think of on the fly:

  1. create some variables for my textual content for personalization purposes
  2. create restricted content inside a block group

Let’s dive right in. Here’s the first scenario in more detail.

Personalized content inside a Gutenberg block

Let’s say you’re creating a sales letter for your newsletter subscribers, or some personalized content for your website subscribers. In that case, you might want to personalize a couple of information details about your audience. Maybe a first name, and perhaps a company that person works for (or owns). A simple personalization of content can go a long way in making your audience feel special and more responsive to your message.

So, if we wanted to do something like this, we can create variable placeholders inside our text, something like this:

  1. {firstname} – we would use this placeholder to insert a first name of our reader
  2. {company} – obviously we’d use this as a placeholder for a company name

So, let’s see how this looks inside a block in our edit screen:

As you can see, we’ve embedded our placeholders inside the textual content. What we aim to do here, is to replace these placeholders with some real world values related to our readers. We can do this in a couple of ways, but in my example, I’ve used two scenarios:

  1. the user is logged into my website, so I can obtain hers/his first name (or username)
  2. the user has clicked on a personalized email link that has contains some URL parameters, for example, https://codeart.studio/some-article-name?firstname=Zelimir&company=CodeART. “firstname” and “company” are URL parameters, followed by their values (after the equation symbol)

The filter I’ll be using to filter the block’s content is “render_block_{$block_name}”. “$block_name” represents a name of the block we’re going to be filtering. In this case, we’re filtering the paragraph block, so the actual filter name is “render_block_core/paragraph”. The value we’ll be filtering here is stored inside the “$block_content” variable that this filter has access to. We’ll also be using the “$block” variable to check for the block’s class name, so we need to declare both of these variables inside our callback functions.

Now, there’s no need to filter every paragraph block on my website, so I’m only going to filter those with a specific class. For this example, I’ll use a class named “userNameBlock”. It seems simple enough to filter by class, as it’s very easy to enter a class name for a block inside the edit screen:

Class name for a Gutenberg block
Class name for a Gutenberg block

I’m going to paste the full code below, and explain line by line what’s going on. I’m going to check for two scenarios while filtering the content:

  1. If a user is not logged in, I’m going to grab both URL parameters (if they exist)
  2. If a user is logged in, I’m only going to fetch the “company” URL parameter and try to get the first name from the user’s profile information

    function codeart_paragraph_block_variables( $block_content, $block ) {

  if ( isset( $block['attrs']['className'] ) && 'userNameBlock' === $block['attrs']['className'] && $_GET['firstname']  && !is_user_logged_in()) {
    $firstname = $_GET['firstname'];
    $company = $_GET['company'];
    if(empty($company)) {
      $company = 'your company';
    }
    $vars = [
      '{username}' => $firstname,
      '{company}' => $company
    ];
    $block_content = strtr($block_content, $vars);

  } elseif ( isset( $block['attrs']['className'] ) && 'userNameBlock' === $block['attrs']['className'] && is_user_logged_in() ) {
      $user = wp_get_current_user();
      $firstname = $user->user_firstname;
      $company = $_GET['company'];
      if(empty($firstname)) {
        $firstname = 'friend';
      }
      if(empty($company)) {
        $company = 'your company';
      }
      $vars = [
          '{username}' => $firstname,
          '{company}' => $company
      ];
      $block_content = strtr($block_content, $vars);

  } 

  return $block_content;
}
add_filter( 'render_block_core/paragraph', __NAMESPACE__ . '\\codeart_paragraph_block_variables', 10, 2 );
Gutenberg block filtered content

First case scenario:

  1. On line 1, we’re declaring our function name, and declaring the variables we’re going to use to filter the content, namely, $block_content (holds the entire content of the block) and $block which holds some relevant information about our block (namely, the class name we’re going to be targeting)
  2. In our first scenario, lines 3 – 13, we’re aiming at the non-logged in users.
  3. Line 3 – other than checking for a particular class name, we’re also checking to make sure we have a URL parameter of “firstname” set, and making sure our user is not logged in
  4. Lines 4 – 8 – we’re getting the URL parameter values. If the “company” URL parameter is not set, we’re setting the variable to the value “your company” (lines 6 – 8)
  5. Lines 9 – 12 – we’re putting our variables inside an array “$vars” that we’re going to use to filter the content
  6. Line 13 – we’re using “strtr” function to replace placeholders with our variable values

Second case scenario:

  1. In our second scenario, we’re aiming at the logged in users (line 15). Other than checking for the logged in user, we’re also checking for a particular block class (“userNameBlock”).
  2. Line 16 – we’re getting the necessary information for our logged in user
  3. Line 17 & 19 – 21 – we’re setting the first name for the user. If there’s no first name set, we’re simply setting the variable value as “friend”.
  4. Everything else is exactly the same in our first scenario, from lines 22 to 29, we’re setting the values for the company name, our variable values for our placeholders, and filtering the block content with “strtr”.

How it works

In our first scenario, we’re aiming at the non-logged in user with URL parameters for the first name and company name. This is what happens when, for example our non-logged in reader loads the page with filtered block content and with a link to our article that holds the URL parameters, such as https://codeart.studio/some-article-name?firstname=Zelimir&company=CodeART:

The same thing happens for the second scenario, except that we’re looking for a user’s first name from the WordPress database instead of through the URL parameter. We’re only fetching the company name from the URL parameter and replacing the placeholder with its value.

Restricted content inside a Gutenberg block

We could restrict the content of a paragraph block, but this does not make much sense (at least for me). It makes much more sense to restrict content for a group block. By doing this, we can cram anything we want, any type of block, inside a group, and restrict access to it. It’s a versatile approach, and quite straightforward.

In my example, I’m going to be restricting access via distinguishing logged in from non-logged in users (only logged in users will have access). I will also use a class name to restrict access, just like in my first example, with the variables. The class name will be “restrictedContent”. So we start by creating some content inside Gutenberg editor, grouping it, and giving it a class name of “restrictedContent”. From the edit screen, it looks like this:

We group our content and give it a class name that we’ll use to target the block content

Once this is done, we create our filter. Once again I’ll paste the code and explain line by line what’s going on below the code:


    function codeart_group_block_restrict( $block_content, $block ) {

  if ( isset( $block['attrs']['className'] ) && 'restrictedContent' === $block['attrs']['className'] && !is_user_logged_in()) {
    $block_content = 'This content is restricted to registered users only. Please <a href="'.wp_login_url().'">login</a> first.';
  }
  return $block_content;

}
add_filter( 'render_block_core/group', __NAMESPACE__ . '\\codeart_group_block_restrict', 10, 2 );
Gutenberg block restricted content
  1. Line 3 – we’re checking for non-logged in users. If a user is not logged in, we’re proceeding with our code. We’re also only targeting group block with a class name of “restrictedContent”.
  2. Line 4 – if we’ve detected a non-logged in user, we replace the variable $block_content (which normally holds the content for the block) with our custom message for the non-logged in user. I’ve put a login form link here, which kind of makes sense for me.

And that’s it. Simple, right? This way you can simply create some teaser content, and restrict access to the rest. The end result is this:

Now, you could expand the restricted content conditions easily to include particular user roles, or some other condition that would make sense, but I wanted to keep it simple as possible for this example.

So, here it is, some quick and easy ways to filter Gutenberg block content. I hope this gives you some fresh new ideas for your next project!

Hire your codeartist

looking for a development of your own project?

is your agency looking for a partner?