我自己设法想出了一个解决办法。要获取特定帖子类型的帖子列表,必须将wp.data.select( \'core\' ).getEntityRecords()
中的选择器withSelect
高阶组件,这是一个使用选择器为组件提供道具的函数。然后,我们可以用这些数据填充SelectControl。
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 );