How to Set Block Defaults Programmatically

Photo of a keyboard with a man holding up a cloud shape next to a lightbulb
License: Adobe Stock

If you’ve spent much time in the block editor, you will inevitably find a block that you often find yourself configuring over and over again. Setting some defaults for the block would save a lot of time. Let’s go over how you can set a block’s settings programmatically so that it comes pre-configured just the way you like it.

Finding the block’s attributes

In order to set a block’s defaults, you’ll need to have some knowledge of the block’s attributes and how they work to form the block.

Here are some ways to find the attributes for the block you are wanting to add a defaults for.

In the plugin’s PHP files with register_block_type

Some older block plugins register their attributes via the function register_block_type.

Function register_block_type takes in two arguments:

  1. The block name or path to block.json file
  2. An array of arguments

This 2nd argument can take in array keys, one of which can be labeled attributes. Here’s a quick example of how the code would look:

Attributes in register_block_type
Attributes in register_block_type

Using terminal and JavaScript commands

Select the block in the block editor, open your console tools in the browser, and type in:

wp.data.select( 'core/block-editor' ).getSelectedBlock().attributes;Code language: JavaScript (javascript)
Getting Attributes in the Block Editor Using Console
Getting Attributes in the Block Editor Using Console

This is by far the easiest way to determine attributes for a block.

In the block’s block.json file

For most blocks, the best way to find the attributes is in the block’s block.json file. In WordPress, this would involve looking at the source code for the blocks and finding the block.json files.

For a button block, for example, I can browse the attributes rather easily using the button’s block.json file.

Button Block Block.json Example
Button Block Block.json Example

If you are trying to find a block.json file in another plugin, here are some tips:

Search for block.json in the plugin’s build folder

A lot of the newer plugin’s use @wordpress/scripts to build their block plugins. This copies a block’s block.json files into the build folder, which is often deployed with the plugin. You can investigate this folder and see if you can find the plugin’s block.json file in order to view the attributes.

For example, here’s how my AlertsDLX block.json files turned out in the build folder.

.
└── alerts-dlx/
    └── build/
        └── js/
            └── blocks/
                ├── bootstrap/
                │   └── block.json
                ├── chakraui/
                │   └── block.json
                ├── material/
                │   └── block.json
                └── shoelace/
                    └── block.jsonCode language: AsciiDoc (asciidoc)

Find the plugin’s GitHub and search for their blocks

Most of the plugins out there have some kind of public version control repository of their plugin. If you find a plugin’s GitHub, chances are the block-related items will be in a src/ or src/blocks folder.

For example, here is Kadence Blocks on GitHub.

Kadence Blocks in the src/blocks Folder
Kadence Blocks in the src/blocks Folder

You can then drill down and view the block.json file.

Kadence Blocks Accordion Block.json File
Kadence Blocks Accordion Block.json File

Setting default paragraph attributes

For our first example, let’s pick on the paragraph block.

I’ll start by selecting a paragraph block in the block editor and pasting in the following to the developer tools console to get the attributes:

Shortcut for Getting a Block's Attributes
Shortcut for Getting a Block’s Attributes
wp.data.select( 'core/block-editor' ).getSelectedBlock().attributes;Code language: JavaScript (javascript)

Here are the attributes I received.

{content: 'Lorem ipsum dolor sit amet, consectetur adipiscing…Mauris massa. Vestibulum lacinia arcu eget nulla.', dropCap: false}Code language: CSS (css)

But that doesn’t give us all the attributes. For Core attributes, it’s pretty easy to drill down and find a block’s block.json file.

For example, here is the paragraph’s block.json file:

{
	"$schema": "https://schemas.wp.org/trunk/block.json",
	"apiVersion": 3,
	"name": "core/paragraph",
	"title": "Paragraph",
	"category": "text",
	"description": "Start with the basic building block of all narrative.",
	"keywords": [ "text" ],
	"textdomain": "default",
	"attributes": {
		"align": {
			"type": "string"
		},
		"content": {
			"type": "string",
			"source": "html",
			"selector": "p",
			"default": "",
			"__experimentalRole": "content"
		},
		"dropCap": {
			"type": "boolean",
			"default": false
		},
		"placeholder": {
			"type": "string"
		},
		"direction": {
			"type": "string",
			"enum": [ "ltr", "rtl" ]
		}
	},
	"supports": {
		"anchor": true,
		"className": false,
		"color": {
			"gradients": true,
			"link": true,
			"__experimentalDefaultControls": {
				"background": true,
				"text": true
			}
		},
		"spacing": {
			"margin": true,
			"padding": true,
			"__experimentalDefaultControls": {
				"margin": false,
				"padding": false
			}
		},
		"typography": {
			"fontSize": true,
			"lineHeight": true,
			"__experimentalFontFamily": true,
			"__experimentalTextDecoration": true,
			"__experimentalFontStyle": true,
			"__experimentalFontWeight": true,
			"__experimentalLetterSpacing": true,
			"__experimentalTextTransform": true,
			"__experimentalWritingMode": true,
			"__experimentalDefaultControls": {
				"fontSize": true
			}
		},
		"__experimentalSelector": "p",
		"__unstablePasteTextInline": true
	},
	"editorStyle": "wp-block-paragraph-editor",
	"style": "wp-block-paragraph"
}Code language: JSON / JSON with Comments (json)

Let’s change the paragraph’s placeholder to better match a client site’s branding.

Setting the plugin header

Let’s begin by setting a new plugin’s header.

<?php
/**
 * Plugin Name:       DLX Change Paragraph Placeholder
 * Plugin URI:        https://dlxplugins.com
 * Description:       Change the placeholder text for the paragraph block.
 * Version:           1.0.0
 * Requires at least: 6.0
 * Requires PHP:      7.3
 * Author:            Ronald Huereca
 * Author URI:        https://mediaron.com
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package DLXChangeParagraphPlaceholder
 */

namespace DLXPlugins\ChangeParagraphPlaceholder;Code language: PHP (php)

Filtering the block metadata

Up next, let’s add a filter for block_type_metadata, which we can use to change the attribute values.

add_filter( 'block_type_metadata', __NAMESPACE__ . '\modify_paragraph_attributes', 10, 1 );Code language: PHP (php)

Providing a callback

The callable callback points to modify_paragraph_attributes, which is the function we’ll use to modify the attributes.

/**
 * Set Paragraph defaults.
 *
 * @param array $metadata {
 *    An array of arguments.
 *
 *    @type string $name       Block name.
 *    @type array  $attributes Block attributes.
 * }
 */
function modify_paragraph_attributes( $metadata ) {
	// Check the block type.
	if ( 'core/paragraph' !== $metadata['name'] ) {
		return $metadata;
	}

	// Add accordion view (collapsed view).
	$metadata['attributes']['placeholder']['default'] = 'Please type or use "/" command.';

	// Return the metadata.
	return $metadata;
}Code language: PHP (php)

Since I know placeholder is one of the attributes, I can change the way a user is prompted for an action.

Placeholder Changes in the Block Editor
Placeholder Changes in the Block Editor

Modifying an image’s default attributes

I recommend trying to find the image’s block.json file since there are many aspect of the image’s core block that can be overridden and are often hidden features. Here is the current location of the image’s block.json file.

The attributes I found are as follows:

"attributes": {
	"align": {
		"type": "string"
	},
	"url": {
		"type": "string",
		"source": "attribute",
		"selector": "img",
		"attribute": "src",
		"__experimentalRole": "content"
	},
	"alt": {
		"type": "string",
		"source": "attribute",
		"selector": "img",
		"attribute": "alt",
		"default": "",
		"__experimentalRole": "content"
	},
	"caption": {
		"type": "string",
		"source": "html",
		"selector": "figcaption",
		"__experimentalRole": "content"
	},
	"title": {
		"type": "string",
		"source": "attribute",
		"selector": "img",
		"attribute": "title",
		"__experimentalRole": "content"
	},
	"href": {
		"type": "string",
		"source": "attribute",
		"selector": "figure > a",
		"attribute": "href",
		"__experimentalRole": "content"
	},
	"rel": {
		"type": "string",
		"source": "attribute",
		"selector": "figure > a",
		"attribute": "rel"
	},
	"linkClass": {
		"type": "string",
		"source": "attribute",
		"selector": "figure > a",
		"attribute": "class"
	},
	"id": {
		"type": "number",
		"__experimentalRole": "content"
	},
	"width": {
		"type": "number"
	},
	"height": {
		"type": "number"
	},
	"aspectRatio": {
		"type": "string"
	},
	"scale": {
		"type": "string"
	},
	"sizeSlug": {
		"type": "string"
	},
	"linkDestination": {
		"type": "string"
	},
	"linkTarget": {
		"type": "string",
		"source": "attribute",
		"selector": "figure > a",
		"attribute": "target"
	}
},Code language: JSON / JSON with Comments (json)

In this particular scenario, I want my image to always be aligned in the center and to link to the full-sized image.

Setting the plugin headers

Let’s set the plugin headers to point to this new name around our image.

<?php
/**
 * Plugin Name:       DLX Change Image Attributes
 * Plugin URI:        https://dlxplugins.com
 * Description:       Change the align and default link settings for an image.
 * Version:           1.0.0
 * Requires at least: 6.0
 * Requires PHP:      7.3
 * Author:            Ronald Huereca
 * Author URI:        https://mediaron.com
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package DLXChangeImageAttributes
 */

namespace DLXPlugins\DLXChangeImageAttributes;Code language: PHP (php)

Finally, we set the callback.

add_filter( 'block_type_metadata', __NAMESPACE__ . '\modify_image_attributes', 10, 1 );

/**
 * Set Image Block defaults.
 *
 * @param array $metadata {
 *    An array of arguments.
 *
 *    @type string $name       Block name.
 *    @type array  $attributes Block attributes.
 * }
 */
function modify_image_attributes( $metadata ) {
	// Check the block type.
	if ( 'core/image' !== $metadata['name'] ) {
		return $metadata;
	}

	$metadata['attributes']['align']['default']           = 'center';
	$metadata['attributes']['linkDestination']['default'] = 'media';

	// Return the metadata.
	return $metadata;
}Code language: PHP (php)

Conclusion

Within this tutorial I went over how to find a block’s attributes, and which filter to use to override them. If you have any questions, please leave a comment.

Ronald Huereca
By: Ronald Huereca
Published On: on July 10, 2023

Ronald Huereca founded DLX Plugins in 2022 with the goal of providing deluxe plugins available for download. Find out more about DLX Plugins, check out some tutorials, and check out our plugins.

1 thought on “How to Set Block Defaults Programmatically”

  1. Pingback: WordPress forces us to use Block editor | Marcus Ampe's Space

Leave Your Valuable Feedback

Your email address will not be published. Required fields are marked *

Shopping Cart
  • Your cart is empty.
Scroll to Top