Run your custom code only once in an action

WordPress offers a lot of hooks you can use to interact with code. Filters are used to change a value of a passed variable, and you usually want to change this value every time this filter is applied. But for actions you might want to run them only once, especially when thy run side effects like sending an email.

Check, if an action has been triggered

With the function did_action() you can check how many times an action has already been called. If you want to run your custom code only when the action is run the first time and then not a second time, you can do the following:

function do_this_only_once() {
	// If the action we are hooking in was called more than once, return.
	if ( did_action( 'the_hook_name' ) > 1 ) {
		return;
	}

	// Run your custom code
}
add_action( 'the_hook_name', 'do_this_only_once' );

When the the_hook_name action is being called and then running did_action( 'the_hook_name' ), the return value will be 1, as the action has just been triggered. Therefore, you can’t simply use its return value as a boolean, but you have to check if the return value is greater than one, to stop the execution of your custom code.

Use your own action to avoid multiple runs of your code

Sometimes you cannot simply break check if the action runs for the first time, but you have to check for additional things. You can add them all to the one condition. Alternatively, you can use your own action, which then you use in the early return condition:

function do_this_only_once( $hook_parameter ) {
	// If the custom code has been run already, return.
	if ( did_action( 'do_this_only_once' ) ) {
		return;
	}

	// A second check on a hook parameter.
	if ( 'something' !== $hook_parameter ) {
		return;
	}

	// Run your custom code

	// Call our custom action, so we can check, if it has been called already.
	do_action( 'do_this_only_once' );
}
add_action( 'the_hook_name', 'do_this_only_once' );

In this code example, we use a custom action in our first condition. Then we perform some other checks, to prevent execution of our custom code, unless we really want to run it. Then we finally run our code. At the very end of the function, we run our custom action, so we can use it on the next call to prevent a second execution. This early return makes sure we not only run the code once, but also that we don’t run the additional conditions again.

Conclusion

There are different ways to make sure to run an action only once. It’s usually best to just use the did_action() function which will tell you how many times an action was run. And if you have some side effects in your code, like sending an email, you really should make sure you don’t run them more times than necessary.

Update all composer dependencies to their latest versions

If you code in PHP, changes are very high that you are using composer to manage your dependencies. At one point, you will add a dependency. The version you’ve first installed can be updated with a single command, but it won’t update to a new major version. If you have a lot of dependencies in an old project, and you want to try, if all the newest versions of them would work (with a current PHP version), you would usually have to update every package separately, by adding it as a dependency again:

composer require wp-cli/mustangostang-spyc
composer require wp-cli/php-cli-tools
...

Now you could just copy/paste every package name from your composer.json file, but for many dependencies, that’s quite a task, and you might miss some. So I was searching for a way to do it in just one command.

Updating all packages at once

For this blog post, I will use the wp-cli/wp-cli package as an example. It has a number of required and dev-required dependencies.

Getting all packages as a list

The first step is to find a command that gives us a list of all composer packages used in the project. We can use the composer show command for this:

$ composer show -s
name     : wp-cli/wp-cli
descrip. : WP-CLI framework
keywords : cli, wordpress
versions : * 2.7.x-dev
type     : library
license  : MIT License (MIT) (OSI approved) https://spdx.org/licenses/MIT.html#licenseText
homepage : https://wp-cli.org
source   : []  a5336122dc45533215ece08745aead08af75d781
dist     : []  a5336122dc45533215ece08745aead08af75d781
path     : 
names    : wp-cli/wp-cli

support
issues : https://github.com/wp-cli/wp-cli/issues
source : https://github.com/wp-cli/wp-cli
docs : https://make.wordpress.org/cli/handbook/

autoload
psr-0
WP_CLI\ => php/
classmap
php/class-wp-cli.php, php/class-wp-cli-command.php

requires
php ^5.6 || ^7.0 || ^8.0
ext-curl *
mustache/mustache ^2.14.1
rmccue/requests ^1.8
symfony/finder >2.7
wp-cli/mustangostang-spyc ^0.6.3
wp-cli/php-cli-tools ~0.11.2

requires (dev)
roave/security-advisories dev-latest
wp-cli/db-command ^1.3 || ^2
wp-cli/entity-command ^1.2 || ^2
wp-cli/extension-command ^1.1 || ^2
wp-cli/package-command ^1 || ^2
wp-cli/wp-cli-tests ^3.1.6

suggests
ext-readline Include for a better --prompt implementation
ext-zip Needed to support extraction of ZIP archives when doing downloads or updates

Here you’ll find sections with the “requires” and “requires (dev)”. But this output is rather hard to parse for the names only. Fortunately, you can get the output as a JSON object as well, by adding the --format argument:

$ composer show -s --format=json
{
    "name": "wp-cli/wp-cli",
    "description": "WP-CLI framework",
    "keywords": [
        "cli",
        "wordpress"
    ],
    "type": "library",
    "homepage": "https://wp-cli.org",
    "names": [
        "wp-cli/wp-cli"
    ],
    "versions": [
        "2.7.x-dev"
    ],
    "licenses": [
        {
            "name": "MIT License",
            "osi": "MIT",
            "url": "https://spdx.org/licenses/MIT.html#licenseText"
        }
    ],
    "source": {
        "type": "",
        "url": "",
        "reference": "a5336122dc45533215ece08745aead08af75d781"
    },
    "dist": {
        "type": "",
        "url": "",
        "reference": "a5336122dc45533215ece08745aead08af75d781"
    },
    "suggests": {
        "ext-readline": "Include for a better --prompt implementation",
        "ext-zip": "Needed to support extraction of ZIP archives when doing downloads or updates"
    },
    "support": {
        "issues": "https://github.com/wp-cli/wp-cli/issues",
        "source": "https://github.com/wp-cli/wp-cli",
        "docs": "https://make.wordpress.org/cli/handbook/"
    },
    "autoload": {
        "psr-0": {
            "WP_CLI\\": "php/"
        },
        "classmap": [
            "php/class-wp-cli.php",
            "php/class-wp-cli-command.php"
        ]
    },
    "requires": {
        "php": "^5.6 || ^7.0 || ^8.0",
        "ext-curl": "*",
        "mustache/mustache": "^2.14.1",
        "rmccue/requests": "^1.8",
        "symfony/finder": ">2.7",
        "wp-cli/mustangostang-spyc": "^0.6.3",
        "wp-cli/php-cli-tools": "~0.11.2"
    },
    "devRequires": {
        "roave/security-advisories": "dev-latest",
        "wp-cli/db-command": "^1.3 || ^2",
        "wp-cli/entity-command": "^1.2 || ^2",
        "wp-cli/extension-command": "^1.1 || ^2",
        "wp-cli/package-command": "^1 || ^2",
        "wp-cli/wp-cli-tests": "^3.1.6"
    }
}

Now we need to parse the JSON. On my Linux system, I had the jq command available, which allows you to parse a JSON file or output. I’ve found a nice cheat sheet with some useful argument and was able to just the get the requires key:

$ composer show -s --format=json | jq '.requires'
{
  "php": "^5.6 || ^7.0 || ^8.0",
  "ext-curl": "*",
  "mustache/mustache": "^2.14.1",
  "rmccue/requests": "^1.8",
  "symfony/finder": ">2.7",
  "wp-cli/mustangostang-spyc": "^0.6.3",
  "wp-cli/php-cli-tools": "~0.11.2"
}

This is great! But we only need the names of the packages, so in the next step, we get the object keys:

$ composer show -s --format=json | jq '.requires | keys'
[
  "ext-curl",
  "mustache/mustache",
  "php",
  "rmccue/requests",
  "symfony/finder",
  "wp-cli/mustangostang-spyc",
  "wp-cli/php-cli-tools"
]

In order to use it in another command, we usually want the names in a single line, so we use add to achieve this:

$ composer show -s --format=json | jq '.requires | keys | add'
"ext-curlmustache/mustachephprmccue/requestssymfony/finderwp-cli/mustangostang-spycwp-cli/php-cli-tools"

Not really what we want. We need a space after every package name. We can add it with map:

$ composer show -s --format=json | jq '.requires | keys | map(.+" ") | add'
"ext-curl mustache/mustache php rmccue/requests symfony/finder wp-cli/mustangostang-spyc wp-cli/php-cli-tools "

We are almost there, we just need to remove the quotes around the string with the -r argument:

$ composer show -s --format=json | jq '.requires | keys | map(.+" ") | add' -r
ext-curl mustache/mustache php rmccue/requests symfony/finder wp-cli/mustangostang-spyc wp-cli/php-cli-tools

And there we have it. Now we can put it into a sub command and finally update all required dependencies at once:

$ composer require $(composer show -s --format=json | jq '.requires | keys | map(.+" ") | add' -r)
Using version * for ext-curl
Info from https://repo.packagist.org: #StandWithUkraine
Using version ^2.14 for mustache/mustache
Using version ^7.4 for php
Using version ^2.0 for rmccue/requests
Using version ^5.4 for symfony/finder
Using version ^0.6.3 for wp-cli/mustangostang-spyc
Using version ^0.11.15 for wp-cli/php-cli-tools
./composer.json has been updated
...

That it! If your project also have dev requirements, you’ll need to run a second command updating them as well by adding --dev to the composer command and using devRequires instead of requires in the filter:

$ composer require --dev $(composer show -s --format=json | jq '.devRequires | keys | map(.+" ") | add' -r)
Using version dev-latest for roave/security-advisories
Using version ^2.0 for wp-cli/db-command
Using version ^2.2 for wp-cli/entity-command
Using version ^2.1 for wp-cli/extension-command
Using version ^2.2 for wp-cli/package-command
Using version ^3.1 for wp-cli/wp-cli-tests
./composer.json has been updated
...

Summary

I hope this blog post explained, how you can use composer and another command to get a task like this done in a single command. These are the two commands again you will probably need:

For required packages:

composer require $(composer show -s --format=json | jq '.requires | keys | map(.+" ") | add' -r)

For development packages:

composer require --dev $(composer show -s --format=json | jq '.devRequires | keys | map(.+" ") | add' -r)

I really like the power of command line tools, but finding a one-liner is sometimes a bit more tricky. After searching for a solution to this very problem, I finally took the time to come up with something, and fortunately I’ve found a solution.

Work and travel – or how coding on a train can be a challenge

Today I want to share a different type of story. When I travel in Germany, I usually always take the train. If some of you ever travelled from Berlin westbound will probably know, that as soon as you leave Berlin, the internet connection gets really bad, no matter if you use the wifi on board an ICE or your mobile as a hotspot. But those of you using Linux and being developer might not even be able to connect to the internet using the wifi at all.

WIFIonICE

When you take an ICE high speed train, even in the 2nd class you will be able to use free wifi. It’s decent enough for most things, even streaming and video calls, if you really need to do them. But please not in a quite zone! For streaming, at iceportal.de you will even find some movies and series to watch, just like in a plane.

That sound nice, right? But you might not be able to use it at all. Usually, you would connect to either WIFIonICE or WIFI@DB and your browser will pop up to ask you to accept the terms. If that’s not happening, open a browser and navigate to LogIn.WIFIonICE.de to see that page. You did that and nothing happens? Then the FAQ section on the DB website might help you. But you wouldn’t be here it that worked, right?

OK, let me take a guess: you might be using a Linux laptop, but you are definitely using for local development you are using Docker. Got it? Then welcome to my uncommon blog post to a strange topic ?

Docker networks and WIFIonICE

The issue is one, you will unfortunately not find on the DB website. And it’s also one I ran into and couldn’t find out, why I was not able to see the page to accept the terms. Any request to any page just failed. Nothing happened in the browser. The reason for that is the following: the ICE on board network uses the 172.17.0.0/16 IP range. And not take a guess what Docker is using as the default IP range for its networks! You are a clever one ?

Solving the issue

In order to be able to connect, you have to remove the network attached to the IP address 172.17.0.1 from your Docker networks. This could be done with the OS tools (like ip link delete) or using the docker network rm command. This would fix it, but it might break things within Docker, as the network you have just deleted is probably needed. Usually its the primary bridge network. And when you board an ICE in some months time, the IP address might again be taken by another Docker network. So I needed a more robust solution.

Change the IP range

After some research, I’ve found the documentation of an optional configuration file you can have on your system to set some variables for the Docker daemon. This page also contains a full example for a Linux configuration. From this, we would only need a small part. First, you open up the configuration file (or create it):

sudo vim /etc/docker/daemon.json

Now you add (at least) the following lines and save the file:

{
  "default-address-pools": [
    {
      "base": "172.30.0.0/16",
      "size": 24
    },
    {
      "base": "172.31.0.0/16",
      "size": 24
    }
  ]
}

I have defined two alternative IP ranges. One would probably have been enough. After changes on this file, you have to restart the Docker daemon. For me, this command did it (on Manjaro Linux):

systemctl restart docker

Now you should be able to open up the page to accept the terms and finally start some productive coding session on the train … or enjoy a movie from the onboard media library ?

Conclusion

Network issues and issues with (public) hotspots is probably something we all can tell many stories about. But I’d never imagined that using Docker would cause an issue, not even DB is aware of. Or at least they don’t have anything in their FAQ about this specific issue, which probably not only I had more than once now. So is this blog post helped you to get online, why not leave a little comment? ☺️

Adding form specific Gravity Form hooks to your code

Those of you who read my blog regularly will probably know, that I use Gravity Forms in many projects. I really like the huge feature set of the plugin (and it’s add-ons), but even more than that, the possibilities to customize things. I’ve also helped to build such an extension, which allows you to bulk download all files of one (or many) entries. This week we have released a new version introducing a small but important feature: the possibility to have form specific hooks.

Hooking into Gravity Forms

When customizing Gravity Forms functionalities, it works just as with Core and plugins/themes. You would use add_action() or add_filter() for your custom code. And Gravity Forms has a lot of actions and filters!

Let’s take the gform_pre_submission action as an example. You can use this action to change the entry before notifications are sent, and before it is saved to the database. A use case might look like this:

function my_gform_pre_submission( $form ) {
    $_POST['input_1'] = strtolower( $_POST['input_1'] );
}
add_action( 'gform_pre_submission', 'my_gform_pre_submission' );

This would take the value of the form field with ID 1 (input_1) and change the text to lower case. This however would do it for every single form you have created. If you just want to do it for one form, you have to use the action specifically for this form. Fortunately, that’s possible by using the dynamic form specific hook names. Just replace the add_action call with this line:

add_action( 'gform_pre_submission_5', 'my_gform_pre_submission' );

This action name has a _5 suffix and will therefore only be called for the form with the ID 5. I’ve already covered this in the blog post Dynamic form specific hooks for GravityForms earlier this year, where I’ve also explained on how to deal with those static form ID values in the hook names.

Now that we have repeated this little introduction, let’s dive into adding such a form specific hook into your own code.

Providing hooks in your custom code

When you want to allow parts of your code being changed by hooks, you have to use one of these two functions:

  1. apply_filters()
  2. do_action()

You can probably guess which one to use for which type of hook. The difference is, that filters return a value while actions do not. So when using a filter, it looks like this:

$value = apply_filters( 'filter_name', $value, $arg1, $arg2 );

You define the filter name, then you pass the value to be filtered. You can also optionally pass more arguments to the filter, which you can then use in your callback function, to decide on how to change the value.

For an action, it looks pretty much the same. But you won’t save the return value, as the function does not return anything:

do_action( 'action_name', $arg1, $arg2 );

As an action does not change a value, it does not necessarily need a value being passed, so all arguments are optional. Many actions take no values at all, like wp_head for example.

Make hooks form specific

Now that we know how we can add hooks to our code, let’s see how we can make them form specific. In the official Gravity Forms documentation, you only find a page for actions, but without too much explanation. But the modifications you have to do are the same for actions and filters. All you have to do is prefixing the two function with gf_ and passing an array with the hook name and the form ID as the first argument. For filters, it looks like this:

$value = gf_apply_filters( array( 'filter_name' $form_id ), $value, $arg1, $arg2 );

In this example, we would need to have the ID of the form stored in a variable $form_id, but you might get it from $form['id'], $entry['form_id'] or similarly. You just have to make sure you pass it. For an action, the new function call would look like this:

gf_do_action( array( 'action_name' $form_id ), $arg1, $arg2 )

That’s really all you have to do!

Conclusion

When you write add-ons/plugins or custom code for Gravity Forms, it’s always nice to think about parts of your code others might want to change. Providing hooks for those parts can make your code so much more useful. And if you add those hooks, always use the Gravity Forms functions, so the hooks can be targeted specifically for individual forms.

Adding some options to a block

After we have seen in the last block post, how we can use modern JavaScript to write a block, I want to show why we would really want to do that by adding some options to our block. I’ll show you only the changes we have to do.

Creating an “edit” component

As a first step, we remove the edit() function from the index.js file and place it in its own file. The index.js file also have the following content left:

import { registerBlockType } from '@wordpress/blocks';
import './editor.scss';
import './style.scss';
import Edit from './edit';
import metadata from './block.json';

registerBlockType(
	metadata.name,
	{
		edit: Edit
	}
);

We import the new Edit component and assign it to options when registering the block. We also remove the import for the ServerSideRender component, as it’s no longer needed in the index.js file.

Implementing the component

Not that we have our new file imported, let’s add the ServerSideRender component again and all the things we would need for our option. The result would look like this:

import ServerSideRender from '@wordpress/server-side-render';
import { InspectorControls } from '@wordpress/block-editor';
import { Disabled, PanelBody, RangeControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useBlockProps } from '@wordpress/block-editor';
import './editor.scss';

export default function Edit( props ) {
	const {
		attributes,
		setAttributes,
	} = props;
	const {
		postsToShow,
	} = attributes;

	return (
		<>
			<InspectorControls>
				<PanelBody
					title={ __( 'Settings', 'rpssrb' ) }
				>
					<RangeControl
						label={ __( 'Number of items', 'rpssrb' ) }
						value={ postsToShow }
						onChange={ ( value ) =>
							setAttributes( { postsToShow: value } )
						}
						min="1"
						max="100"
					/>
				</PanelBody>
			</InspectorControls>
			<div { ...useBlockProps() }>
				<Disabled>
					<ServerSideRender
						block="rpssrb/random-posts"
						attributes={ attributes }
					/>
				</Disabled>
			</div>
		</>
	);
}

OK, this is a whole lot more than we had before. But let’s look at each part to understand what’s happening here.

Step 1: Importing components

In our new code, we need some React components. We will get them from different WordPress packages. We import all of them in the lines 2-5.

Step 2: Creating a function and getting the component properties

We create a function Edit and also export it as the default function right away, so it can be used in our index.js file, as we have seen in the first code snippet. The “edit” and “save” function automatically get some properties. We can “extract” those properties we need. The attributes property is an object with the attributes to the specific block. It uses a React state to live update the UI in the block editor every time a value changes. The setAttribute property is a function that is used in combination with attributes to update the state object.

As attributes is an object as well, we can also get some values from it and assign it to separate variables. We will do that with the postsToShow attribute, we will use later.

Step 3: Implementing the inspector controls

Now that we have the attribute we want to change, we can implement the controls to adjust them. The first thing that might look a little weird is that “empty tag” <> at line 12. This is necessary as the function can only have one root tag in its return statement. We basically just wrap the rest of the JSX tags wight this empty tag.

Next, we open the <InspectorControls> component, which holds all the item in the block sidebar. Inside of that, we create a <PanelBody> to have a nice title for our option, and then we add a <RangeControl> component. The result will look like this:

The InspectorControls with a PanelBody and the title "Settings" as well as a RangeControl with the label "Number of item" with a selected value of 5.

Now we have a nice little “range slider” with which we can select the number of posts to show. With the min and max attributes of the component, we define the limits of the control. The initial value will be retrieved from the previously defined postsToShow attribute and on the onChange event, we use the setAttribues function to update the value in the state. If some of these things don’t make sense at first, you’ll get familiar with them the longer you use them.

Step 4: Rendering the block

Now that we have our controls to adjust the number of posts, we need to render them in our new Edit component. We will again use the <ServerSideRender> component, but this time we add the attributes to the tag, so that the component will refresh, every time we change the value of the posts to show.

We also wrap the component inside a <div>, so we can attach all the blog properties, and we also use a <Disabled> components, so we are able to select our block in the block editor (and not opening the permalinks instead).

Step 5: Registering the attribute for the block

Any time you use an attribute for a block, you have to register it. This is done in the block.json file. The new file looks like this:

{
	"$schema": "https://schemas.wp.org/trunk/block.json",
	"apiVersion": 2,
	"name": "rpssrb/random-posts",
	"version": "0.1.0",
	"title": "Random Posts",
	"category": "widgets",
	"icon": "smiley",
	"description": "An example for a ServerSideRender block using minimal ES6 code.",
	"supports": {
		"html": false
	},
	"textdomain": "random-posts-server-side-render-block-es6",
	"attributes": {
		"postsToShow": {
			"type": "number",
			"default": 5
		}
	},
	"editorScript": "file:./index.js",
	"editorStyle": "file:./index.css",
	"style": "file:./style-index.css"
}

Step 6: Using the options in the PHP callback function

Now that we can set the option and save it, we have to use it in our PHP callback function. But fortunately that is really easy, as it is passed automatically into the function:

function rpssrb_render_callback( $atts ) {
	$args = [
		'post_type'      => 'post',
		'orderby'        => 'rand',
		'posts_per_page' => (int) $atts['postsToShow'],
	];

	// Run the query and render the posts as in the previous blog posts ...
}

This was it! I’d suggest you to look into the different components you can use in the block editor handbook. There are many you may find really useful to build your block options. Just make sure you register those new attributes as well.

Conclusion

I know this was a lot more code than in the previous two blog posts. But once you have the basics set up for the “inspector controls” you can add new controls as you want.

As I’ve explained in the first blog post to this small series, you can also split up files as much as you want. If the inspector controls get really complex, you might want to move them to their own file. But for this example I’ve wanted to keep it simple again and only use the one edit.js file.

A first simple block with some ES6 code – it’s not as scary as it sounds

I’m currently on vacation and had some tech free days, so my blog post comes a bit later this week. In the previous post, I’ve shown you, how you can write a block without any ES6/React code. This week I want to show you the minimum you have to know to get the full potential of modern JavaScript while still keeping it simple.

Create a block with the “create-block” script

As I’ve also mentioned, that I would highly recommend using the create-block package to create your first little plugin. This will create a lot of files for you, and you are ready to go. We create the example from the last post by running this command in the wp-content/plugins folder:

npx @wordpress/create-block random-posts-server-side-render-block-es6

This will give you the following files in the newly created plugin directory:

$ tree
.
├── node_modules
├── package.json
├── random-posts-server-side-render-block-es6.php
├── readme.txt
└── src
    ├── block.json
    ├── edit.js
    ├── editor.scss
    ├── index.js
    ├── save.js
    └── style.scss

In the node_modules folder we will have all the files we would need for compiling the ES6 code so browsers can use them. The package.json defines all the dependecies that are installed as well the scripts that would run.

The block definition

The most important file in a “block plugin” is the src/block.json file. It defines the name, title, icon and other details:

{
    "$schema": "https://schemas.wp.org/trunk/block.json",
    "apiVersion": 2,
    "name": "rpssrb/random-posts",
    "version": "0.1.0",
    "title": "Random Posts",
    "category": "widgets",
    "icon": "smiley",
    "description": "An example for a ServerSideRender block using minimal ES6 code.",
    "supports": {
        "html": false
    },
    "textdomain": "random-posts-server-side-render-block-es6",
    "editorScript": "file:./index.js",
    "editorStyle": "file:./index.css",
    "style": "file:./style-index.css"
}

At the end of the file you will find three really useful lines. They define where the asset files are located. So while we had to use wp_enqueue_scripts in the last blog post, we get this all for free. No need to do that in PHP and handling the check for this file, it’s dependecies and the timestamp for caching ourselves. Just this one feature make it worth using a bit more of modern block development.

Now you could still write only ES5 code into the JavaScript files, but let’s take a look on how our simple example look like with modern JavaScript.

Registering a server side rendered block with ES6

As you have seen in the file system output above, you usually get three JS files. The index.js file will register the block. The edit.js file is used for rendering the block in the editor including controls for it’s options. The save.js will finally hold the functions to save the block content into the post content. Those two extra files can be used, but for a simple block you can also just use the index.js file. And for really complex blocks you would even split up the edit.js into smaller (reusable) parts. To keep it simple again, we will just use the index.js file:

import ServerSideRender from '@wordpress/server-side-render';
import { registerBlockType } from '@wordpress/blocks';
import './editor.scss';
import './style.scss';
import metadata from './block.json';

registerBlockType(
    metadata.name,
    {
        edit() {
            return (
                <ServerSideRender
                    block="rpssrb/random-posts"
                />
            );
        }
    }
);

In order to use components and functions in ES6, we have to import them. We are going to use the ServerSideRender component as well as the registerBlockType function. When you compare this code snippet with the ES5 one from the last blog post, you will recognize that it does not look all that different. This “weirdly looking HTML tag” is JSX, an extension to HTML that React is using to build its components. When passing parameters to those components, you are using attributes similar to HTML (instead of using a JSON object, as in the ES5 variant) and in those attributes you can even use JavaScript. For our ServerSideRender component, we only need to pass the static block name.

As you might have recognized, we are getting the name for the block in the registerBlockType function from our metadata we also import. This will give us the opportunity to get any of the declared values from this file. In this very simple example, we only need the name. We could also use this in the block attribute of the ServerSideRender component, but here we just use a static string.

The two lines I have not yet covered are the imports for the SCSS files. When you use the @wordpress/scripts package that being installed with the npx command above, you will get Sass compilation for free. You just name the two files editor.scss and style.scss and they will be compiled for either just the block editor or for the front end as well.

Now, after you have written this beautiful code, you finally have to compile it. If you only want to do it once (in a minified way, suitable for production use), you run npm run build or while actively developing you use npm run start so you always have a (verbose version, which is better for debugging) of the code you just write.

Registering the PHP callback function for the server side rendered block

As we are still writing a block that would get its content from the PHP backend, we also still have to register the callback function. It looks quite similar to our previous code. But instead of using static string, we can also use the index.js file to register the block in PHP and adding the callback function parameter:

function create_block_rpssrb_block_init() {
	register_block_type(
		__DIR__ . '/build',
		[
			'render_callback' => 'rpssrb_render_callback',
		]
	);
}
add_action( 'init', 'create_block_rpssrb_block_init' );

Instead of using the blocks name, we use the path to our build directory that is being created using the build scripts. In this folder, the PHP function will look for an index.js file and use the block name from this file.

We also use the same implementation for our callback function you can find in the previous blog post. And again you can also use the “bonus” of having a shortcode for the callback as well.

Conclusion

It’s really not that hard to create a block using ES6 syntax, and using the create-block package (or using the @wordpress/script package) make the hard part of getting the compilation running a lot easier. The only thing you have to do – and what might be a bit though – is installing node and then installing npm on your machine. Even then, you have to keep these two up to date and working with the packages you are using. This can really be annoying from time to time.

The reason why it’s worth to do all that, I will cover in my next blog post, when we add some simple controls to our block to make it more usable.

Replace a shortcode with a block using as little and simple code as possible

Earlier this week, Topher asked an interesting question on Twitter regarding the current state of block development:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

This made me think about I would answer this question. When I first started with block development, I primarily wrote “server side rendered blocks”. These blocks will not generate the content directly in the editor, but use some PHP code and a callback function to render the content, just as a shortcode would do.

The other difficulty with block development is the need to learn many new things: React, JSX, modern JavaScript compilation with webpack and much more. This all combined does not make it “as easy” as it was with shortcodes. But still I wanted to show, how little code you need to create a block that could possibly replace a shortcode without the need to learn all these new things.

Writing a server side rendered block – the PHP part

The easy part is registering the block and the render callback in PHP. While you would use the function add_shortcode() for a shortcode callback, you use a parameter when registering the block in PHP:

function rpssrb_init() {
	register_block_type(
		'rpssrb/random-posts',
		[
			'render_callback' => 'rpssrb_render_callback',
		]
	);
}
add_action( 'init', 'rpssrb_init' );

For this blog post, we will write a block that will render some random posts. The content of the callback would look just like with a shortcode. You can also use the same helper functions you would use for a shortcode. The callback might look like this:

function rpssrb_render_callback( $atts ) {
	$atts = shortcode_atts(
		[
			'post_type'      => 'post',
			'orderby'        => 'rand',
			'posts_per_page' => 5,
		],
		$atts
	);

	$query = new WP_Query( $atts );

	$output = '';
	if ( $query->have_posts() ) {
		$output .= '<ul>';
		while ( $query->have_posts() ) {
			$query->the_post();
			$output .= sprintf(
				'<li><a href=%s>%s</a></li>',
				get_permalink(),
				get_the_title()
			);
		}
		$output .= '</ul>';
	}

	return $output;
}

We set some default attributes and then run a WP_Query to get 5 random posts. We render them in a simple unordered list with only the title linked to the blog post.

Implementing the block in JavaScript – using ES5 code only

As mentioned before, one of the hardest parts of writing a block is need to learn React, JSX, etc. and compile this code. If you are not familiar with these technologies, it can be really hard to get started. This is why I want to show you how you can use some ES5 (“old JavaScript”) to write a block. All you really need is this:

wp.blocks.registerBlockType(
	'rpssrb/random-posts',
	{
		title: 'Random Posts',
		edit: function () {
			return wp.element.createElement(
				wp.serverSideRender,
				{
					block: 'rpssrb/random-posts'
				}
			);
		}
	}
);

We use the wp.blocks.registerBlockType function in ES5 style and only provide a title and the edit function. In this function, we create a React element with the wp.serverSideRender component that will render our block.

The edit function is used to show the content of the block (in our case the result of the callback function written in PHP). You don’t even need this, but then you would not see anything in the block editor (the block also does not take up any space as it’s empty), but it would render in the frontend.

Loading the JavaScript file

This JavaScript code has to be loaded when the block editor is used. If you already have some files being loaded for the block editor, just place it in this file. If not, you would enqueue it in the same way as usual, but with a different hook:

function rpssrb_register_scripts() {
	wp_enqueue_script(
		'random-posts-server-side-render-block',
		plugin_dir_url( __FILE__ ) . 'index.js',
		[ 'wp-blocks', 'wp-server-side-render' ],
		filemtime( plugin_dir_path( __FILE__ ) . 'index.js' ),
		true
	);
}
add_action( 'enqueue_block_editor_assets', 'rpssrb_register_scripts' );

In the dependencies, we add wp-blocks and wp-server-side-render, but they are usually loaded anyway when the block editor is used.

Bonus: use a shortcode as well

As we have written a callback function that we already know from shortcodes, we can simply add another line to make it usable as a shortcode as well (e.g. using the shortcode block):

add_shortcode( 'rpssrb_random_posts', 'rpssrb_render_callback' );

Caveat: using attributes is complicated!

The block we have built here cannot use any attributes. Adding them to the block would be easy, but implementing the controls to make them usable is not that easy. And while it’s doable using only ES5, I would not suggest doing this.

Consequence: Learn JavaScript, deeply.

As Matt has given us all as homework at WCUS 2015 I would highly suggest to start learning some modern JavaScript. The hardest part is getting started is the compilation using webpack. If you have no idea where to start, I would agree with the answer from Birgit to the tweet: use the create-block package.

The create-block package will not only help you to create a running block inside a WordPress plugin. It will also install all the JavaScript packages needed to compile the modern JavaScript. For this it’s using the @wordpress/scripts package and the main script you would use is the start script. Give it a try, read some documentation on how to add attributes and make your block even easier to use.

Conclusion: creating a block can be easy, but it might not be enough

While you can write a block as a simple replacement for a shortcode using only one PHP and one JavaScript file using ES5 syntax, I would not recommend it. Once you made yourself familiar with some basics, you can create blocks that improve usability dramatically. I know it sounds a bit intimidating, and you will run into all kinds of problems, but it’s worth it.

If you want to see the complete code of this blog post, you can find it on GitHub as a plugin.

WordCamp Europe 2022 – The community finally meets in Porto

It’s been three year. Three years after we had our last WordCamp Europe with attendees meeting in person, 2019 in Berlin. Back then I was the Local Lead and joined the next organizing team as one of three Global Leads. Then the pandemic changed the world and WordCamps became online events. While this year’s WCEU was not the first in person event, it was the biggest one, and it felt – almost – as in the past.

My first trip to Portugal

In 2020, I was supposed to visit Porto to see the venue we would use for WCEU 2020, but the pandemic hit us all, and we moved the WordCamp online and cancelled all local organizing work. Then this year in February there was another venue visit, this time for the new organizing team, but unfortunately I got COVID just some days before that. So on Monday, 30 May, I finally made it to Portugal for the first time.

Preparing the event

On Tuesday, I had the chance to get a first view of the amazing venue, the Super Bock Arena – Pavilhão Rosa Mota. The crew was already preparing the expo area and the screen for track 1:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

I had also the chance to meet some members of the organizing team for the first time in person and had lunch with some of them. As most things were already done or managed by the various teams, I had some time on Wednesday evening to visit the “Pirate Party” including a cruise on the river:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

Kicking it off with the Contributor Day

Like many other WordCamps we also had a Contributor Day organized on Thursday.

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

The Contributor Day took place in front of the stage of track 1. We had around 800 contributors, many of them first time contributors. This was a new record for any WordCamp!

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

The first conference day

Friday was the first day with talks and workshops. The contributing tables were replaced by seating for the talks:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

I had the honor to open WordCamp Europe 2022 with our Local Team Jose Freitas and the three other Global Lesley Molecke, Moncho (José Ramón Padrón García) and Taeke Reijenga:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

Unfortunately, I couldn’t see any talks on the first day. Only the first a half of Maja’s talk, before I had to rush out for some organizing work to be done.

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

Just as in Berlin in 2019 we had more than just talks and workshops. We continued with the “Wellness Track”, offering yoga and meditation in the beautiful park around the venue, had the WP Café format where attendees could discuss topics, and we even had a live-streaming studio. Here we had interviews with different people from the event, which were live-streamed to the feed of track 1 in the breaks between talks. I also had the chance to be interviewed in one break:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

The second conference day

Saturday was the last day of WordCamp Europe. That day usually flies by pretty fast for organizers. At the end of the day we had around 2304 attendees in Porto and just before lunch many of them came together for a family photo:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

The last talk of WordCamp Europe 2022 was a Q&A session with Josepha and Matt:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

After this talk, it was time for the closing remarks. We had 91 organizers and 164 volunteers helping us making this all possible and having a great in-person event:

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

As always, we announced the city for the next WordCamp Europe at the end of the closing remarks and welcomed the new team …

WordCamp Europe 2022 Athens

Next year, the WordPress community will meet in Athens, Greece! Another country I have not yet visited.

Click here to display content from Twitter.
Learn more in Twitter’s privacy policy.

Time to “hang my hat”

For me, this was the last WordCamp Europe as an organizer. I’ve joined the team back in 2017 and only took a break last year for the second online edition. Following the “tradition” of being a Local Lead and then a Global Lead, I will probably be speaking next year, maybe sharing the stage with my fellow Global Leads from 2020 and 2022. As much as I loved organizing all these events, it’s time to make room for new community members to step up and join the team. I’m very much looking forward to what the WCEU 2023 crew will surprise us with!

Make changes to PHP ini values without losing them on an update

If you have ever set up a server yourself, you probably realized, that the default values for PHP don’t really work for modern websites. The upload_max_filesize is set to only 2 MB, which means that you cannot upload anything into the media library of WordPress that is larger than 2 MB. This value is usually one you want to change for any site. But how can you change the value and not risking your modifications to be reverted, one you upgrade PHP or your server.

Changing the global PHP ini values

This blog is running on Ubuntu 22.04 with PHP-FPM running alongside the nginx web server. If I want to make changes to any PHP ini variable, I would make those changes to the file /etc/php/8.1/fpm/php.ini on a global level. As you can see in the file path, you would have to make these changes to the php.ini file of each installed PHP version. You would also need to do the change for any “server API”, so if you also use CGI/FastCGI for some site, you have to make the same changes to the file /etc/php/8.1/fpm/php.ini as well.

The advantage of this change is that any website hosted on this server will use these settings, so you can set good defaults for any site. But as you make changes to global configuration files, you will run into issues once you upgrade your server. When the package manager wants to upgrade the configuration file, it detects changes and asks you to either use the new file, use your modified file or to examine the changes and resolve them yourself. Depending on how many changes you have made, this might be difficult to make.

In order to modify PHP ini values globally, I have added a new file called /etc/php/conf.d/90-custom.ini with only the variables I want to change and them symlink them into the different configuration paths:

$ tree /etc/php/   
/etc/php/
|-- 7.3
|   |-- cgi
|   |   |-- conf.d
|   |   |   |-- 10-mysqlnd.ini -> /etc/php/7.3/mods-available/mysqlnd.ini
|   |   |   |-- ...
|   |   |   `-- 90-custom.ini -> /etc/php/conf.d/90-custom.ini
|   |   `-- php.ini
|   |-- cli
|   |   |-- conf.d
|   |   |   |-- 10-mysqlnd.ini -> /etc/php/7.3/mods-available/mysqlnd.ini
|   |   |   |-- ...
|   |   |   `-- 90-custom.ini -> /etc/php/conf.d/90-custom.ini
|   |   `-- php.ini
|   |-- fpm
|   |   |-- conf.d
|   |   |   |-- 10-mysqlnd.ini -> /etc/php/7.3/mods-available/mysqlnd.ini
|   |   |   |-- ...
|   |   |   `-- 90-custom.ini -> /etc/php/conf.d/90-custom.ini
|   |   |-- php-fpm.conf
|   |   |-- php.ini
|   |   `-- ...
|-- ...
|-- 8.1
|   |-- cgi
|   |   |-- conf.d
|   |   |   |-- 10-mysqlnd.ini -> /etc/php/8.1/mods-available/mysqlnd.ini
|   |   |   |-- ...
|   |   |   `-- 90-custom.ini -> /etc/php/conf.d/90-custom.ini
|   |   `-- php.ini
|   |-- cli
|   |   |-- conf.d
|   |   |   |-- 10-mysqlnd.ini -> /etc/php/8.1/mods-available/mysqlnd.ini
|   |   |   |-- ...
|   |   |   `-- 90-custom.ini -> /etc/php/conf.d/90-custom.ini
|   |   `-- php.ini
|   |-- fpm
|   |   |-- conf.d
|   |   |   |-- 10-mysqlnd.ini -> /etc/php/8.1/mods-available/mysqlnd.ini
|   |   |   |-- ...
|   |   |   `-- 90-custom.ini -> /etc/php/conf.d/90-custom.ini
|   |   |-- php-fpm.conf
|   |   |-- php.ini
|   |   `-- ...
|-- ...
|-- conf.d
|   `-- 90-custom.ini

As the new 90-custom.ini is not a file that package manager would add/update, any changes made in this file would be safe from upgrades.

Changing PHP ini values per site

Sometimes you want or need to change values for a specific site. Then using the global file would not work. If you are using the Apache web server, you might be able to change values using the Apache configuration files or even using the .htaccess file. In this file, you would use something like php_value upload_max_filesize 64M to increase the upload limit. This, although, will only work if you use PHP as an Apache module.

If you use Apache with PHP-FPM or different web server – like I am using nginx – you cannot use the .htaccess file to make any changes to the PHP ini values.

Using the “user_ini” file for per site changes

Fortunately, you have another way to change PHP ini values. This can be done with a “user_ini” file, you usually store in the document root of the site. First, you have to find out what the filename for this file should be. You can find out with the phpinfo() function or by running php -i and searching for the user_ini.filename value. You then create this file and add any changes writing it in the same way as in the php.ini files, so like upload_max_filesize = 64M to change the upload limit.

When you make changes to this file and check if they work, they probably don’t! This does not mean that, that you’ve made a mistake. It probably means that the file was not read by the PHP process. This is because the file is cached. You can find out for how long by looking at the user_ini.cache_ttl value. This is the time, in seconds, the file is cached. If the value is 300, you have to wait up to 5 minutes for changes to be used for the site. If you need the changes to be used immediately, you have to restart the PHP process (like PHP-FPM) or the web server (when you use Apache mit mod_php).

Conclusion

There are multiple ways to make changes to PHP ini variables. When you have to make changes, always make sure to use a method that would not break upgrades (or the changes getting lost with the upgrade). For my own server, I prefer to use the first approach with a global custom ini file. The user_ini file has the advantage that these value could easily be transferred to a new server when migrating a site, so they might be better for PHP systems that need specific values.

Fixing the Matomo opt-out iframe when using secure headers

Last year, I wrote a blog post about how to secure your website with server headers. When changing the security headers, there is always the chance that some things stop working, as they need “more unsecure” settings. One of these example is the Matomo opt-out iframe and in this blog post I want to show you how to solve it.

The opt-out gets blocked by the browser

If you use Matomo to track your visitors and collect statistics on how they use your site, it’s best to always use the most privacy-friendly settings. You should run the tracking without cookies and also enable the “Do Not Track” option. But even with these settings, you should allow your visitors to opt-out from tracking. To do this, you can create an iframe in the privacy settings of Matomo. This iframe is usually added to your privacy page. If you do this with secure headers set for Matomo, you might get the following error message in browsers:

Refused to display ‘https://matomo.example.com/’ in a frame because it set ‘X-Frame-Options’ to ‘sameorigin’.

This happens when the security headers are too tight not allowing a website with a different domain to embed them.

Allow external domains

One thing you could do now is changing the value of the X-Frame-Options to something more insecure. But we don’t really want that. Instead, you can explicitly allow some domains to embed the iframe. This can be done using the Content-Security-Policy header:

Apache

Header set Content-Security-Policy "frame-ancestors 'self' https://example.com/ https://www.example.com/"

nginx

add_header Content-Security-Policy "frame-ancestors 'self' https://example.com/ https://www.example.com/"

You might already have a Content-Security-Policy set in your server headers. In this case, you can also add these options to the existing header. If you don’t know how to combine different options, the generator from Report UI may be you with this.

Conclusion

Securing a website is very important. But sometimes a higher level of security can interfere with other things. Always make sure to test all things after changing something on the server headers. If visitors are unable to opt-out from tracking, you might have solved a potential security issue, but now you have a privacy issue.