Skip to content

Instantly share code, notes, and snippets.

@joemaller
Created December 18, 2024 17:14
Show Gist options
  • Save joemaller/8d54a186cdc81815cca46a6a96de63d5 to your computer and use it in GitHub Desktop.
Save joemaller/8d54a186cdc81815cca46a6a96de63d5 to your computer and use it in GitHub Desktop.
Quick explanation of accessing Post data in the WordPress block editor

Kind of a silly breakthrough, but I seem to have finally nailed down how to access Post data inside a custom block with useSelect. I'm not going to bother quoting the official docs, they're extensive but hard to follow. Instead, here's the chunk of code I wanted to document and remember, it exposes the full Post object to the Block Editor:

const post = useSelect(
  (select) => select("core").getEntityRecord("postType", postType, postId),
  [postId]
);

Let's walk through that, outside-in:

  • useSelect is called with two arguments, the first is a function, and the second is an array of inputs to use as memoization cache keys
    • The function in the first argument will be called with one arguement: another select function which accesses the internal WordPress data stores. In this case "core" is shorthand for importing from @wordpress/core-data from @wordpress/core-data. Presumably, the argument is the same select function as can be imported from @wordpress/data.
      • select('core') is chained and returns an entityRecord for this postType and postId (assuming a valid ID).

So, a function is called with a function, which accesses a data store, which is passed to a selector, which may or may not return a value. Simple!

useSelect also seems to be doing something which re-runs the first argument whenever state changes.

10up has a very good explanation of the WordPress datastores here: https://gutenberg.10up.com/guides/data-api/

Memoization is a simple caching pattern where a function's results are stored using the inputs as keys. If the function is called again with the same keys, the result is delivered from the cache/store instead of running the whole process again. This is very good for computationally heavy functions, but probably a waste of effort and too much cognitive load for simple stuff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment