day 58…

  • Accessing post meta
  • useSelect

When we add any dynamic blocks, we need to use meta data related to the post to display in the block, like for a movie its runtime, release date are all metadatas

How to access them in the WordPress blocks, when it comes to the PHP render callback that we use the API is pretty strightforward and easy to use inside the query loop to get the metadata.

For the use in blocks Edit function, we can use the data store of the WP using the useSelect hook, from that we can get the post data but how to get the meta, for that we can use the useEntityProp hook

const [meta, updateMeta] = useEntityProp(
		'postType',
		'rt-movie',
		'meta',
		movie.id
	);

Then we can access the meta data one by one

const releaseDate = meta['rt-movie-meta-basic-release-date'];
	const director = PersonPosts(meta['rt-movie-meta-crew-director']);
	const actors = PersonPosts(meta['rt-movie-meta-crew-actor']);
	const runtime = meta['rt-movie-meta-basic-runtime'];

I have created this simple function that parses the metadata and gets the posts for us

const PersonPosts = (metaValue) => {
	const metaArr = JSON.parse(metaValue);

	const posts = useSelect((select) =>
		select('core').getEntityRecords('postType', 'rt-person', {
			include: metaArr,
		})
	);
	return posts;
};

removeEditorPanel :

The function provides a way to remove a editor panel, it can be useful when in our theme or plugin we want to override some functionality and remove existing panels.

```js
await wp.data.dispatch('core/edit-post').removeEditorPanel('post-excerpt');
```

We can customize the editing experience for the clients, maybe even apply some authorization on the editing experience.


IF our blocks are not fully dependent on the server side, we don’t have to register them in the block registry of the server, we can register them only on the front end and make them work.

registerBlockType('mlb/myfirst', {
	title: "My First Block",
	category: 'text',
	icon : 'smiley',
	edit: Edit,
	save: Save,
});

Dynamic Blocks and the attributes!!!

I encountered an issue while creating dynamic blocks. The save function was returning null, and the block render callback was defined in PHP. How are the attributes stored?

I was trying to give the attributes types like number, boolean, etc., but no matter what, in the editor, they won’t work because the save function was not there.

The attributes are getting stored in the database post, but when rendering in the block editor, their types change. In the DB, they are stored as a string, but we have defined them as different types in our block.json.

To fix it, we can just change their type to string.

"attributes": {
		"count": {
			"type": "string",
			"default": 5
		},
		"director": {
			"type": "string"
		},
		"genre": {
			"type": "string"
		},
		"label": {
			"type": "string"
		},
		"language": {
			"type": "string"
		}
	},

Comments

Leave a Reply

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