Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Last active July 5, 2019 14:43
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 markhowellsmead/bb01144b61b242dbca5a108c9eaaab9e to your computer and use it in GitHub Desktop.
Save markhowellsmead/bb01144b61b242dbca5a108c9eaaab9e to your computer and use it in GitHub Desktop.
React Component for Gutenberg - Post Selector using `withSelect`
const { _x } = wp.i18n;
import editMask from './postSelector.jsx';
wp.blocks.registerBlockType( 'sht/clubgallery-teaser', {
title: _x('Bildergalerie - Teaser', 'Block title', 'sha'),
icon: 'format-gallery',
category: 'sht/custom',
supports: {
align: [
'wide', 'full'
],
anchor: true,
html: false
},
attributes: {
post: {
type: 'string',
default: ''
}
},
edit: editMask,
save() {
return null;
}
});
const { _x } = wp.i18n;
const { ServerSideRender, PanelBody, SelectControl } = wp.components;
const { select, withSelect } = wp.data;
const { InspectorControls } = wp.editor;
const { Component } = wp.element;
class PostSelector extends Component {
constructor() {
super( ...arguments );
}
setPost( post ) {
const { setAttributes } = this.props;
setAttributes( { post } );
}
/**
* Must return a single DOM node, hence the anonymous wrapper
*/
render() {
const { attributes, name, selectOptions } = this.props;
const { post } = attributes;
return (<>
<InspectorControls>
<PanelBody title={_x( 'Block Options', 'Editor panel title', 'sha' )} initialOpen={true}>
<SelectControl
label={_x( 'Bildgalerie auswählen', 'Select field label', 'sha' )}
value={post}
options={selectOptions}
onChange={this.setPost.bind( this )}
/>
</PanelBody>
</InspectorControls>
<ServerSideRender block={name} attributes={attributes}/>
</> );
}
}
export default withSelect( ( select, props ) => {
const { getEntityRecords } = select( 'core' );
const POST_TYPE = 'clubgallery';
const POST_LIST_QUERY_PARAMS = {
per_page: -1,
orderby: 'title',
order: 'asc'
};
let selectOptions = [{
label: _x( 'Auswählen', 'Default selector label', 'sha' ),
value: ''
}];
let posts = getEntityRecords( 'postType', POST_TYPE, POST_LIST_QUERY_PARAMS );
if ( !posts ) {
return posts;
}
posts.map( post => {
selectOptions.push( { value: post.id, label: post.title.raw } );
} );
return {
selectOptions: selectOptions
};
} )( PostSelector );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment