I work with WordPress sites that have lots of meta fields exposed through the REST API. Within Gutenberg, I’m often checking those values by querying the meta attribute in the data. Sometimes the large number of meta fields makes it difficult to find the specific fields I’m interested in. To make my life easier, I’ve put together a code snippet that filters the keys in the meta object that is returned.
This is the command I run where mysubstring is the string I’m looking for in the meta keys.
((substring) => Object.fromEntries(
Object.entries(
wp.data.select('core/editor').getEditedPostAttribute('meta')
).filter(
([key, value]) => key.toLowerCase().includes(substring.toLowerCase()
)
)))('mysubstring')
How It Works
First Retrieve meta Attribute in Gutenberg Block Editor
Running this in the browser console while on our Gutenberg page, returns a list of the meta fields exposed in the REST API.
wp.data.select('core/editor').getEditedPostAttribute('meta');
e.g.
{
my_color: 'red',
mastodon_post: 'https://phpc.social/@salcode/115684016910550967',
mastodon_server: 'https://phpc.social/',
}
If there are lots of fields this response could be unpleasant to wade through.
Convert Object to An Array of Arrays
We’re using Object.entries()) to convert our meta object from something like
{
my_color: 'red',
mastodon_post: 'https://phpc.social/@salcode/115684016910550967',
mastodon_server: 'https://phpc.social/',
}
to an array of arrays like
[
[ 'my_color', 'red' ],
[ 'mastodon_post', 'https://phpc.social/@salcode/115684016910550967' ],
[ 'mastodon_server': 'https://phpc.social/'],
]
Filter the Arrays
Then .filter(([key, value]) => key.includes("mastodon") to filter to array to keep only the inner arrays that include our string (mastodon)
[
[ 'mastodon_post', 'https://phpc.social/@salcode/115684016910550967' ],
[ 'mastodon_server': 'https://phpc.social/'],
]
Convert the Array of Arrays Back to An Object
Finally we use Object.fromEntries() to convert the remaining entries back to an object
{
mastodon_post: 'https://phpc.social/@salcode/115684016910550967',
mastodon_server: 'https://phpc.social/',
}
Leave a Reply