My notes on JavaScript available methods in Gutenberg.
Update post meta template to "my-template" for current post
wp.data.dispatch('core/editor').editPost({ meta: { template: 'my-template' } });
Update post title (in the editor)
wp.data.dispatch( 'core/editor' ).editPost( { title: 'My title' } );
Get Post Status
wp.data.select( 'core/editor' ).getEditedPostAttribute( 'status' );
Update Post Status (does not save)
editPost
wp.data.dispatch('core/editor').editPost({ status: 'publish' });
updatePost
const post = wp.data.select('core/editor').getCurrentPost();
post.status = 'publish';
wp.data.dispatch('core/editor').updatePost(post);
savePost
wp.data.dispatch('core/editor').savePost();
wp.data.subscribe
Listen for any changes to the state (note: a value must change to trigger this, this is different behavior than Redux)
wp.data.subscribe(() => { console.log('A change occurred'); });
List for any changes to the state, and display the value of the “Stick to the top of the blog” checkbox.
wp.data.subscribe(() => {
console.log(
'The state of the "Stick to the top of the blog" checkbox is ' +
wp.data.select( 'core/editor' ).getEditedPostAttribute('sticky')
);
});
Dispatch a Notice
wp.data.dispatch('core/notices').createInfoNotice('Hello World');
Get Post Meta Values
wp.data.select( 'core/editor' ).getEditedPostAttribute('meta');
Also the snippet below is helpful and comes from Filter Meta in WordPress Gutenberg Block Editor
((substring) => Object.fromEntries(
Object.entries(
wp.data.select('core/editor').getEditedPostAttribute('meta')
).filter(
([key, value]) => key.toLowerCase().includes(substring.toLowerCase()
)
)))('mysubstring')
Get Post ID
wp.data.select('core/editor').getCurrentPostId()
Get Post Type
wp.data.select('core/editor').getCurrentPostType()
Get Current User
wp.data.select("core").getCurrentUser().id;
wp.data.select("core").getCurrentUser().slug;
wp.data.select("core").getCurrentUser().name;
Change Title of Current Post
wp.data.dispatch( 'core' ).editEntityRecord(
'postType', 'post',
wp.data.select('core/editor').getCurrentPostId(),
{ title: 'Hello World' }
);
npmjs WordPress org
This is also a good place to start chasing things down.
https://www.npmjs.com/org/wordpress
wp.apiFetch()
Often along with these commands I find myself using wp.apiFetch() to update something on the server.
e.g.
postId = wp.data.select('core/editor').getCurrentPostId();
await wp.apiFetch({
path: `wp/v2/posts/${postId}`,
method: 'POST',
data: {
content:"<!-- wp:paragraph --><p>This is my text in a paragraph</p><!-- /wp:paragraph -->",
},
});
Leave a Reply