2022: An eventful year

I usually don’t post “New Years” blog posts – I usually only have a post on the blog’s birthday – but as it’s still the last calendar week of 2021, and I’m unsure if I have to post something for #project26, I will tell you a bit about this new year from my perspective.

#project26 continues

This is either my last blog post of last year or the first one of this year ūüėČ Even though there are some things coming up this year, I will try to continue posting bi-weekly. I will also try to comment on other blogs, but I really struggle even reading lots of blog posts.

WordPress releases and Full Site Editing (FSE)

This year might be the first one with four major releases of WordPress. With the upcoming version 5.9 later this month, we will get a new default theme: TwentyTwentyTwo! So this year I’m finally planning to create my first FSE theme, either in a client project or by rewriting my currently used theme.

Retiring a plugin

With the release of 5.9 there will also be a new feature: the language switcher on the login screen. With this new feature, one of my first two plugins can finally be retired.

WordCamp Europe 2022 … in Porto!

The main “event” for me will be WordCamp Europe 2022, which will finally be held in Porto! Our organizing team is working hard to bring the community together. But as corona/covid will still be around, we will make sure, to also make it as safe for everyone as possible. After this edition, I will also retire from organizing WCEU – at least for some time.

Conclusion

The last two years have been tough for many of us. Finally, 2022 looks like the year we can enjoy some of the things we love! I can’t wait to see many of you either in Porto or on another WordCamp this year! With FSE being almost there, I also think that I will have some great topics to write about.

Using Block Patterns for new entries of a Custom Post Type

When developing projects, I often use Custom Post Types (CPT). In a new project, the content of the entries were build completely with core blocks. In the past, I typically used custom meta fields and a fixed page template. But as creating such a complex content of a CPT is quite a lot of work and error-prone, I wanted to use a template for new entries.

Creating a block pattern

The easiest way to create a pattern for a post type is by creating the content first using the block editor and then exporting the HTML markup using the “Copy all content” option:

Now you can use this markup to register a block pattern with the default content of new entries:

function cpt_register_block_pattern() {
	register_block_pattern(
		'my-cpt/my-cpt-pattern',
		array(
			'title'       => __( 'My CPT pattern', 'my-cpt' ),
			'description' => _x( 'The custom template for my_cpt', 'Block pattern description', 'my-cpt' ),
			'content'     => '
<!-- wp:paragraph {"placeholder":"Custom Post Type ..."} -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:columns -->
<div class="wp-block-columns"><!-- wp:column -->
<div class="wp-block-column"><!-- wp:image -->
<figure class="wp-block-image"><img alt=""/></figure>
<!-- /wp:image --></div>
<!-- /wp:column -->

<!-- wp:column -->
<div class="wp-block-column"><!-- wp:heading {"placeholder":"Name ..."} -->
<h2></h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"placeholder":"Phone ..."} -->
<p></p>
<!-- /wp:paragraph --></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->',
		)
	);
}
add_action( 'init', 'cpt_register_block_pattern' );

Creating a template for new entries

When registering a new CPT, you can can also create default content by passing a template argument with a multidimensional array defining the template:

function cpt_register_post_type() {
	register_post_type(
		'my_cpt',
		array(
			'label'                 => __( 'Custom Post Type', 'my-cpt' ),
			'supports'              => array( 'title', 'editor' ),
			'public'                => true,
			'show_ui'               => true,
			// ... other settings
			'has_archive'           => true,
			'show_in_rest'          => true,
			'template'              => array(
				array(
					'core/paragraph',
					array(
						'placeholder' => __( 'Custom Post Type ...', 'my-cpt' ),
					),
				),
				array(
					'core/columns',
					array(),
					array(
						array(
							'core/column',
							array(),
							array(
								array(
									'core/image',
								),
							),
						),
						array(
							'core/column',
							array(),
							array(
								array(
									'core/heading',
									array(
										'level'       => 2,
										'placeholder' => __( 'Name ...', 'my-cpt' ),
									),
								),
								array(
									'core/paragraph',
									array(
										'placeholder' => __( 'Phone ...', 'my-cpt' ),
									),
								),
							),
						),
					),
				),
			),
		)
	);
}
add_action( 'init', 'cpt_register_post_type' );

As you can see in this little example, the array can get very complex, unreadable and hard to maintain. You would also have to convert the Block Pattern HTML to this PHP array format. So any change to the pattern would require you to do the work twice, trying not to make any mistake.

Combining Block Patterns and Custom Post Types templates

As the solution with the PHP array was not really something I wanted to use (the actual template was a lot more complex than the one shown in the example), I first tried the following:

// ...
'template'              => array(
	array(
		'my-cpt/my-cpt-pattern',
	),
),
// ...

I thought, that maybe the template can also use Block Patterns in the array and not only blocks. But this didn’t work. When searching for a solution, I found multiple issues on GitHub. There I found the core/pattern block, which makes the task very easy:

'template'              => array(
	array(
		'core/pattern',
		array(
			'slug' => 'my-cpt/my-cpt-pattern',
		),
	),
),

Unfortunately, the core/pattern block is not available in WordPress 5.8, but you can already use it with the Gutenberg plugin installed and activated. I really hope that it’s going to be available with WordPress 5.9 expected next month.

Conclusion

Both Block Patterns and templates for new Custom Post Type entries are really helpful. Combining them with the new core/pattern block can really increase usability a lot.

Debugging PHP functions in WordPress

When developing a plugin or theme, you sometimes want to debug one specific function. This function might be used in a larger context, which makes debugging quite difficult and/or slow. Let’s take the example of a function used in a shortcode (or server side rendered block) for example:

function my_shortcode_callback( $atts ) {
	$atts = shortcode_atts( array(
		'post_id' => '',
		// ...
	), $atts, 'my_shortcode' );

	$result = my_function_to_debug( $atts );

	return sprintf(
		__( 'Posted on %1$s by %2$s', 'my-textdomain' ),
		date_i18n( get_option( 'date_format' ), $result['date'] ),
		get_the_author_meta( 'display_name', $result['author'] )
	);
}
add_shortcode( 'my_shortcode', 'my_shortcode_callback' );

In this callback, we now call the function we want to debug. This function can be simple or very complex. Let’s take this one as an example:

function my_function_to_debug( $atts ) {
	$post = get_post( (int) $atts['post_id'] );
	// Maybe do something with the post and create some result
	// ...

	// Dummy result: select two values from the post
	$result = [
		'date'   => $post->post_date,
		'author' => $post->post_author,
	];

	return $result;
}

If you do this in a normal way, you would have to create a page/post and add the shortcode, so the callback and the function to debug get called. Let’s assume you want to debug the shortcode with a lot of different arguments. Then you have to insert multiple shortcodes on one page/post or even create multiple posts/pages.

Debug using the WP-CLI

One of the methods I’m using to debug such a function is using the WP-CLI. Here you can run code “with a WordPress environment” using the wp shell command. This is how this may look like:

$ wp shell
wp> my_function_to_debug( [ 'post_id' => 1 ] );
=> array(2) {
  ["date"]=>
  string(19) "2021-09-26 21:57:32"
  ["author"]=>
  string(1) "1"
}

After starting the shell, we just call the function and pass the arguments we want to test the function with. As the function returns an array, we get the result with a var_dump visualization.

In the same way we could also debug the shortcode callback, or any other function from any plugin/theme or WordPress core:

$ wp shell
wp> my_shortcode_callback( [ 'post_id' => 1 ] );
=> string(34) "Posted on 5 December 2021 by wapuu"

The benefit of this debugging technique is that it will not have to render a (frontend) page/post. It will “only” load the WordPress environment and then execute the function. This is a done lot faster and easier. You also don’t have to create a page using this shortcode.

Debug the function using an AJAX callback

The only issue with this approach can be, that debugging a function using XDEBUG is not (easily) possible, as XDEBUG usually only works in combination with an HTTP request. You could run such a request on the shell using curl, but then you also have to create a page/post with the shortcode and the arguments. Instead, you can “misuse” an AJAX callback function to execute the function in an HTTP request:

function my_ajax_callback() {
	$result = my_function_to_debug( [ 'post_id' => 1 ] );
	var_dump( $result );
}
add_action( 'wp_ajax_my_ajax_action', 'my_ajax_callback' );

Now you run an HTTP request to the URL /wp-admin/admin-ajax.php?action=my_ajax_action (either in a browser or the terminal) and you will get the same var_dump result. This time tough, you can set breakpoints for your debugging with XDEBUG.

Conclusion

Debugging a function does not always require a huge setup of pages/posts to call functions you want to test. With the help of the amazing WP-CLI or the use of an AJAX callback, this can be done a lot easier and faster.

Video documentation of a WordPress installation in the backend

While working on a client’s website this week, I found one very nice thing, I want to share with all of you. On the dashboard I found a widget with a YouTube video of a recorded training session.

Adding a video to the dashboard

The solution used on this client website was done with a custom dashboard widget, and the URL to the video could be set on a large settings page the agency was using to define various options for different features of the WordPress installation.

I thought that this video was really an amazing idea, and my first intention was to implement something like this myself. But “unfortunately”, there is usually a plugin for such a thing implemented by someone else. So while I could not code another plugin, I found some potential plugin. The most basic one is Video Dashboard by Brian Johnson. Here you can add up to 50 videos from YouTube or Vimeo and also control the minimum role someone needs to have to see the videos. A similar plugin is Videos on Admin Dashboard. Here you can only add up to 2 YouTube or Vimeo videos and also control the role. Interestingly, the plugin seems to use the same option names as the other plugin, because if you set video URLs in the other plugin, they will also be used in this one.

Conclusion

Adding a video to the admin dashboard is really a very clever and useful way to help people getting a documentation of a WordPress installation. Using a platform like YouTube or Vimeo, you probably want to make sure that those (individual) videos are not listed or limited to a specific domain (e.g. with Vimeo Pro).

So, how do you offer documentation to WordPress installations? Do you also use (hosted) videos, another type of WordPress documentation plugin or an external documentation tool?

Overwriting the “Register” link

In a previous blog post, I wrote about how I used Gravity Forms to register users. This was done on a static page and not on the default WordPress registration page. When you want users to register using a different form, you should link to this page on many different places. In this blog post I want to show you how you can link to your own registration page from the login page.

The WordPress login page

In the “General Settings” you can activate the “Membership” option “Anyone can register” so that anyone can find a link on the login page that links to the default registration page:

The WordPress login page

If you just want to overwrite the URL of that link, you can use a filter. This get passed the HTML code of the link, which you can overwrite like this:

function custom_register_link( $link ) {
	return sprintf(
		'<a href="%s">%s</a>',
		esc_url( '/register/' ),
		esc_html__( 'Register' )
	);
}
add_filter( 'register', 'custom_register_link' );

This will set the link to the static URL /register/ using the default link text.

This approach only work then you have activated the registrations in the settings. But this would also make the default registration form available. If you haven’t activated the registration, you can still use Gravity Forms (or probably other plugins) to register users. But as the “Register” link is completely removes, you cannot simply overwrite its URL. In this case, we can also place a link on a different place using the following code:

function custom_login_site_html_link( $home_link ) {
	$register_link = sprintf(
		'<a href="%s">%s</a>',
		esc_url( '/register/' ),
		esc_html__( 'Register' )
	);

	return sprintf(
		'%s<br /><br />%s',
		$register_link,
		$home_link
	);
}
add_filter( 'login_site_html_link', 'custom_login_site_html_link' );

This filter is usually used to hook into the “‚Üź Go to <sitename>” link. This is the only place we can insert a custom link into. The result would look like this:

The WordPress login page with a custom “Register” link

This link might even be a bit more visible than the link on the default position, just before the “Lost your password?” link.

Conclusion

Allowing users to register themselves with your own registration form can really be beneficial. If you use a custom form, then make sure to always link users to this form.

Fixing the “Illegal mix of collations” WordPress database error

When updating projects I also check the log files. In a project I maintained, I recently found the following error in the log files I have never seen before:

WordPress database error Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_unicode_520_ci,COERCIBLE) for operation 'like' ...

As WordPress is not very strict with collations, your own WordPress website might also use different collations on different tables. In this project, there were six collations!

Fixing the collations

I order to eliminate this error, we have to convert all tables to use compatible collactions. It’s usually best to use only one collation for all of them. With WordPress 4.2.0 the collation utf8mb4 became the new standard. All database tables created after this update will be created with one of these collation variants. So for our single new collation, we use one of them.

Backup your database

STOP! Before we do anything with our database, we should create a backup. Changing the collation should not be an issue, but in any case it’s always best to create a backup. Use your favorite tool to create the backup. I usually use the WP-CLI for that:

wp db export

Now we can safely do the changes and roll back if things go wrong.

Changing the collation of one table

When changing anything for a database or table, we usually use the ALTER statement which we can also use here as followed:

ALTER DATABASE wp_project_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;

This first statement will set the collation of the whole database, so when you create a new table using a database management tool, this collation will be used. But it will not change it for any of the tables. To do that, we have to alter the tables as well like this:

ALTER TABLE wp_project_name.wp_posts CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;

This one statement would alter the wp_posts. Repeat the same for all other tables. Alternatively you can use the options provided by your database tool to change the collations.

Updating databases with lots of tables

The project I got this error was a multisite installation with 12 sites and 344 tables! That’s not fun updating all of these manually. Fortunately I found a nice little trick in a which will generate all the ALTER TABLE statements for all your tables:

SELECT CONCAT("ALTER TABLE ",TABLE_SCHEMA,".",TABLE_NAME," CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;") 
FROM information_schema.TABLES
WHERE TABLE_SCHEMA="wp_project_name";

Just set your database name in the last line and run it. Then copy all the “generated” queries form the result and run them. Your might run into errors like this:

Invalid default value for 'comment_date'

Then just set the sql_mode temporarily by adding this statement before all the ALTER TABLE statements:

SET sql_mode = '';

Once all statements have finished successfully all tables should now have the same collation. In this example I’ve used utf8mb4_unicode_520_ci but on your server it might be a different variant.

Updating collations using a plugin

While writing this blog post I stumbled upon the Database Collation Fix plugin which can also do this task for you, in case you cannot use a database management tool or you don’t feel like running SQL statements. The only “downside” is, that the plugin will only convert tables to utf8mb4_unicode_ci (or three alternative collations) and not to the newer utf8mb4_unicode_520_ci collation. But this should generally not be an issue.

Conclusion

Even after working with WordPress for so many years there are still some errors I have never seen. In this case it was not an error specific for WordPress, but the way WordPress is handling collations can lead to this issue. Especially if you work with WordPress installations that have been around for a while (probably installed before version 4.2.0). So if you find the same error in your log files, now you should have an idea on how to solve it. And if you haven’t looked into the log file for a while, this blog post might be a reminder to check them.

Generate a dynamic username with the Gravity Forms User Registration add-on in a multisite

As mentioned in previous blog post, I use Gravity Forms quite often when creating forms. It also offers some great add-ons. One of this add-ons is the User Registation. With the help of this extension, you can create a WordPress user, after the form was submitted.

The “username” field

You basically set up a regular form. In this form you should ask for some manadtory fields you would need to create a user account. As a bare minimum, your should ask for an email address, so users can activate their account. Other fields might be first and last name. But what about a username? The add-on offers a special field for usernames. When you want to enable users to pick their own name, this is a perfect field to add.

Use the “email” field

As WordPress allows any user to login either with their username or with their email address, they might not even need to know their username. So when creating the “Feed” to create a user, you could just use the email field. Unless you are creating users for a multisite.

Create a dynamic username using other fields

In a multisite installation, a username can only contain lower case letters and numbers. This is because the username “can” be used for a subsite per user. But even if you don’t plan to have a site per user (which the add-on could also create for you), this constraint still applies. So how to deal with that without asking your users to pick their own username? Simply create a dynamic username using other fields.

Use the first and last name fields

On many platforms, your username will automatically be a combination of your first and last name. So we can use a filter to create such a username. But as this username may still contain some invalid characters, we have to “sanitize” it. Fortunately WordPress offers a function for that. And as two new users may have the same first and last name, we need to find a way to solve that as well. But let’s start with the callback function to the Gravity Forms hook first:

function gf_ms_get_unique_username( $username, $feed, $form, $entry ) {
        // Get first and last name from the form submission.
        $first_name = rgar( $entry, rgars( $feed, 'meta/first_name' ) );
        $last_name  = rgar( $entry, rgars( $feed, 'meta/last_name' ) );

        // Generate a new username making it compatible with multisite constraints.
        $new_username = gf_ms_uf_get_unique_username( sanitize_user( $first_name . $last_name ) );

        if ( ! empty ( $new_username ) ) {
                $username = $new_username;
        }

        return $username;
}
add_filter( 'gform_username', 'gf_ms_uf_set_username', 10, 4 );

Here we use the hook gform_username which is used for the special username field. In the callback we get the values from the first and last name fields and pass them to our helper function to generate a unique username. If we get a new username, we return it.

Generating a unique username

Now how do we get this unique username? Well, we just need a method similar to the one that WordPress uses to get unique permalinks for posts/pages/terms with the same name. We use a “counter suffix” until the username is unique:

function gf_ms_get_unique_username( $username ) {
        $number            = 2;
        $original_username = $username;

        while ( username_exists( $username ) || gf_ms_signup_exists( $username ) ) {
                $username = $original_username . $number ++;
        }

        return $username;
}

function gf_ms_signup_exists( $username ) {
        global $wpdb;

        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM $wpdb->signups WHERE user_login = %s",
                $username
            )
        );
}

In the while loop we check not only if the username already exists, but also if the username has been used by a previous user who already signed up, but hasn’t confirmed his account using the activation link received by mail. To check this, we use another helper function with code similar to the one in Core.

Conclusion

WordPress does offer a native way to sign up new users – to single sites or multisite. But if you want to ask the new users for additional information, an add-on like the one from Gravity Forms can really improve the sign-up process. Signing up users for a multisite can be tricky, but with some good helper functions, this can also be solved. As always, you can find the code from this blog post in a GIST where you can also download it as a ZIP and install it as a plugin.

Get a custom primary navigation per page

In my last blog post I wrote about how to create a simple landing page template. In the text I’ve also mentioned, that you might want to create a custom navigation for the pages you create using this page template. In this blog post, I want to show you how to do that.

Create a menu for a landing page

First, we need to create a custom menu for the landing page. This can be done in either the customizer or the “Appearance -> Menues” section in the admin backend. For the name of the new menu, it’s easiest to use the same name as for the page slug. This will make sure that we can find the custom menu later.

Overwriting a menu by a custom menu

After we have created a new menu with the page slug, we have to dynamically use this new menu. Every menu item is saved in the database as a post type nav_menu_item. The menu itself is a nav_menu taxonomy term. When WordPress tries to load a menu for a menu location, it would query for this taxonomy. Here we can use a filter to get our custom menu with the following code:

function current_page_wp_get_nav_menu_object( $menu_obj, $menu ) {
	if ( $menu_obj instanceof WP_Term && 'primary' == $menu_obj->slug ) {
		$current_slug  = get_post_field( 'post_name', get_the_ID() );
		$page_menu_obj = get_term_by( 'slug', $current_slug, 'nav_menu' );

		if ( $page_menu_obj ) {
			$menu_obj = $page_menu_obj;
		}
	}

	return $menu_obj;
}
add_action( 'wp_get_nav_menu_object', 'current_page_wp_get_nav_menu_object', 11, 2 );

In line 2, we check for the menu location. If we forget to add this step, we would overwrite any menu on the page. So even footer menus, social menus, etc. In this case we will check for the location name primary, the main menu position of your theme may have a different name.

After this check, we get the current slug of the page, try to get the nav_menu term for this term and if we have found it, we will overwrite the original $menu_object to use our custom page menu.

Conclusion

Overwriting a template file is quite easy. Dynamically overwriting a menu being use on a specific position is not possible using template files, but becomes quits easy when using the right filter. Using this little code, you can now have a custom menu per landing page. If you just want to use the same custom menu, when using the page template from the blog post before, you can alternatively check in the filter, if the page template is used and then load another menu.

How to create a landind page without a plugin

A new client is using multiple WordPress plugins to create “landing pages”. Some of these plugins have been removed from the plugin directory. They will not receive any (security) update in the future. In a call it became clear, that we had very different ideas of what a landing page actually is.

What is a landing page

There is not a single best definition of what a landing page is. For me, it can be as simple as a single static page on your website, that presents all the information necessary to reach it’s primary goal. The page is reachable by a permalink and this link can either be found with the right keywords on a search engine or is used in social media posts.

Landing pages can be more complex depending on the goals they want to achieve (like selling things, getting new customers, etc.) and can use techniques to track their success in different ways.

A simple landing page

Many people would argue, that a landing page has no, or just a very limited navigation. Visitors would usually “navigate” from a landing page to another page (shop, checkout, registation, etc.) use “call to action button”. So on a complex website with a huge navigation, a sidebar and a large footer, those elements might want to be removed. But you might not have to use a plugin to do that, as WordPress offers an easier method for this.

Creating a “landing page” template

When you create a page, you can pick a “Template” in the “Page” (or “Post”) tab in the block editor. Those templates are offered by your theme (if it has some), but you can also create them in your child theme. You can find more information on how to create page templates in the Theme Handbook but often you simply copy the page.php, singular.php or index.php file, rename it (usually those files are prefixed with “page-“) and add a comment to the beginnig of the file with the name:

<?php
/**
* Template Name: Landing Page
*/

Just below that you usually find a call to get_header() which will load the header.php file from the theme. This is another place where we might want to customize our landing page template by using a different header. For this you pass a string to the function:

get_header( 'landing-page' );

If call the function like this, WordPress will try to find a file header-landing-page.php instead of the default file. Just copy the header.php as well, rename it accordingly. Now you can be creative in this new file. You can remove the navigation menu all together, use a different navigation position or even change things like logo, etc. in this template.

Creating content for the landing page

Now we are done with our new (and maybe reduces) header, we can continue with the content of the landing page. But this is quite simple the block editor offers all elements you need for a simple landing page, including easy to use buttons.

The future of landing pages

While this approach still needs some custom code, there is a new way in sight to create landing pages: Full Site Editing! Once this is available in WordPress (and themes), you no longer have to create page templates in a child theme. You simply customize the layout of the entire page. So adding/removing navigation menus will be become as easy as writing the content of the page. Then special landing page plugins really need to offer something important, that would justify using another plugin.

Checking your domain security with Mozilla Observatory

In the last two blog posts I have presented two tools I use a lot. This week I want to continue with a third tool, that I have already briefly mentioned in my blog post Better security for WordPress with secure server headers: the Mozilla Observatory tool.

HTTP Observatory

When you run the tool for a domain, you first get an overview about the HTTP security. This was the part I’ve talked about in my previous blog post. The summary of the result may look like this:

Read more →