Enhancing Calls to Action using WordPress Button Block with Default “nofollow” Attributes

Calls to action (CTAs) are an integral part of the internet. Whether you’re encouraging users to subscribe to a newsletter, make a purchase, or read more content, CTAs guide users toward completing specific actions that are beneficial to your site’s goals.

One of the most common ways to implement CTAs is through the use of “button” styles. These visually appealing elements stand out on a page, making it easy for users to know exactly where to click to take the desired action. In WordPress, this is made even simpler with the Core Button block, which allows you to create these calls to action with ease.

However, there’s a common requirement that can make managing these buttons a bit cumbersome: the rel attribute. Often, you’ll need to set the rel attribute to nofollow for your buttons, especially if they link to external sites. This tells search engines not to follow these links, which can be important for your site’s SEO and security.

Remembering to set the nofollow attribute for every button block can be a tedious task, but fortunately, there’s a way to streamline this process. By filtering the button block attributes upon registration, we can add a nofollow default to the rel attribute using a simple piece of code. This ensures that every button you create with the WordPress Button block will automatically include the nofollow attribute, saving you time and effort.

Here is how you do it using Block Filters:

import assign from 'lodash/assign';
import { addFilter } from '@wordpress/hooks';

addFilter(
	'blocks.registerBlockType',
	'kopepasah/core/button/nofollow',
	( settings, name ) => {
		if ( name === 'core/button' ) {
			return assign( {}, settings, {
				attributes: assign( {}, settings.attributes, {
					rel: {
						default: 'nofollow',
						type: 'string',
						source: 'attribute',
						selector: 'a',
						attribute: 'rel',
						__experimentalRole: 'content',
					},
				} ),
			} );
		}

		return settings;
	}
);

While CTAs are essential for guiding users through your site, optimizing their attributes can make a significant difference in your site management. This small tweak can greatly enhance your workflow, allowing you to focus more on creating compelling content and less on repetitive tasks. Happy coding!

Know Caveat

When making this modification on an existing site, your button blocks will likely break since the save element has changed. The way to approach this is to add a deprecation, but it is not the intention of this article.