Blue skies over green trees in the park

How To Use WordPress Data Package To Get The Current Post Being Edited In The Post Editor

In a recent post, I showed how to insert blocks in the WordPress post editor. In this post, I will show how to use the data package, to get the current post’s state. The data module uses the “selectors” and “dispatchers” pattern from Redux. Selectors are functions that return specific data from the data store. Dispatchers are functions that change data in the data store. This post is about selectors.

This page in the documentation has all of the selectors.

Imports Versus wp.data

The examples in this post use wp.data, which works in the editor, with no build steps.

const dispatch = wp.data.dispatch
const select = wp.data.select
//or
const {select,dispatch} = wp.data

Or you can use an import

import {select,dispatch} from '@wordpress/data'

Important note, you can’t use wp.data until the dom ready event

wp.domReady( function(){
  wp.data.select ...
});

Getting Blocks

Get All Blocks In Post

wp.data.select("core/block-editor").getBlocks();

Getting Post State

Get Post Title

wp.data.select("core/editor").getEditedPostAttribute( 'title' );

This gets the ids of tags.

Get Post Categories

wp.data.select("core/editor").getEditedPostAttribute( 'categories' );

This gets the ids of all categories currently set for the post.

Get Post Tags

wp.data.select("core/editor").getEditedPostAttribute( 'tags' );

This gets the ids of tags currently set for the post

Creating A React Hook

In my AI-assisted writing plugin, I have a hook that combines these all, that I use in a few places:

/**
 * Hook That gets data from the post we need for prompt request
 *
 * @return {Object} - object with getData function
 */
export const usePostData = () => {
	const getData = ( length = 1 ) => {
		const categories =
			select( 'core/editor' ).getEditedPostAttribute( 'categories' );
		const tags = select( 'core/editor' ).getEditedPostAttribute( 'tags' );
		const title = select( 'core/editor' ).getEditedPostAttribute( 'title' );
		const post = select( 'core/editor' ).getCurrentPost();
		const data = {
			categories,
			tags,
			title,
			post: post ? post.id : 0,
			length,
		};
		return data;
	};
	return { getData };
};

Finding More Selectors

The data module in the block editor, uses Redux. When I’m figuring out which selectors to use, I open up Redux devtools and watch which actions are fired when I click on stuff in the editor. The other thing I do is open the JavaScript console in Chrome and type wp.data.select(“core/block-editor”), this outputs the name of each selector, which can then be called in the console.

New eBook

Refactoring WordPress Plugins

The PHP Parts

 For experienced WordPress developers who are looking to improve the PHP in their plugins, use new modern best practices and adopt test-driven development.