Skip to content

Instantly share code, notes, and snippets.

@aduth
Created October 2, 2018 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aduth/b4534f62f8919514720af387aabbd4d1 to your computer and use it in GitHub Desktop.
Save aduth/b4534f62f8919514720af387aabbd4d1 to your computer and use it in GitHub Desktop.
Data Module - withSelect & withDispatch
( function( blocks, element, data, components, compose ) {
var el = element.createElement;
blocks.registerBlockType( 'my-demo/demo-block-select', {
title: 'Demo Block (Select)',
icon: 'format-aside',
category: 'common',
edit: data.withSelect( function( select ) {
return {
status: select( 'core/editor' ).getEditedPostAttribute( 'status' )
};
} )( function ( props ) {
return el( 'div', {}, props.status );
} ),
save: function () {
return null;
}
} );
blocks.registerBlockType( 'my-demo/demo-block-dispatch', {
title: 'Demo Block (Dispatch)',
icon: 'format-aside',
category: 'common',
edit: compose.compose( [
data.withSelect( function( select ) {
return {
status: select( 'core/editor' ).getEditedPostAttribute( 'status' )
};
} ),
data.withDispatch( function( dispatch ) {
return {
onChange: function( newStatus ) {
dispatch( 'core/editor' ).editPost( { status: newStatus } );
}
};
} ),
] )( function ( props ) {
return el(
components.SelectControl,
{
value: props.status,
options: [
{ label: 'Publish', value: 'publish' },
{ label: 'Draft', value: 'draft' },
{ label: 'Auto Draft', value: 'auto-draft' }
],
onChange: props.onChange
}
);
} ),
save: function () {
return null;
}
} );
} )(
window.wp.blocks,
window.wp.element,
window.wp.data,
window.wp.components,
window.wp.compose,
);
<?php
/*
* Plugin Name: Demo Block
*/
function demo_block_init() {
wp_register_script(
'demo-block',
plugins_url( 'blocks.js', __FILE__ ),
array(
'wp-blocks',
'wp-element',
'wp-edit-post',
'wp-data',
'wp-editor',
'wp-compose',
)
);
register_block_type( 'demo/demo-block', array(
'script' => 'demo-block',
) );
}
add_action( 'init', 'demo_block_init' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment