I managed to come up with a solution myself. To get a list of posts of a specific post type one must wrap the wp.data.select( 'core' ).getEntityRecords()
selector inside the withSelect
higher order component, which is a function that provides props to a component using selectors. Then, we can populate a SelectControl with this data.
export const settings = {
title: __( 'Post Selection', 'plugin-domain' ),
category: 'common',
attributes: {
id: {
type: 'integer',
default: 0,
},
},
edit: withSelect( ( select ) => {
return {
posts: select( 'core' ).getEntityRecords( 'postType', 'my_custom_post_type', { per_page: -1 } )
};
} )
( props => {
const { attributes, className } = props;
const setID = value => {
props.setAttributes( { id: Number( value ) } );
};
if ( ! props.posts ) {
return __( 'Loading...', 'plugin-domain' );
}
if ( props.posts.length === 0 ) {
return __( 'No posts found', 'plugin-domain' );
}
var options = [];
options.push( {
label: __( 'Choose a post...', 'plugin-domain' ),
value: ''
} );
for ( var i = 0; i < props.posts.length; i++ ) {
options.push( {
label: props.posts[i].title.raw,
value: props.posts[i].id
} );
}
return (
<Placeholder
key='post-selection-block'
icon='admin-post'
label={ __( 'Post Selection Block', 'plugin-domain' ) }
className={ className }>
<SelectControl
label={ __( 'Select a post:', 'plugin-domain' ) }
value={ attributes.id }
options={ options }
onChange={ setID }
/>
</Placeholder>
);
} ),
save( { attributes } ) {
... omitted for brevity ...
},
};
registerBlockType( 'my/postselectblock', settings );