How to populate a select field with post titles/ids in a block

Question

I need to build a really simple block with just one select field. This select field should be populated with the titles/ids of posts of a specific post type. Once a user selects one post from this select field, its id should be saved in a particular attribute.

I have most of the code written, I just need to complete the part that populates the select field with all the posts of a specific post type published in my site.

I know that I must use the wp.data.select( 'core' ).getEntityRecords() selector somewhere, but I have no idea how to start. Any help would be appreciated.

export const settings = {
    title: __( 'Post Selection', 'plugin-domain' ),
    category: 'layout',
    attributes: {
        id: {
            type: 'integer',
            default: 0,
        },
    },

    edit: props => {
        const attributes = props.attributes;

        const setID = value => {
            props.setAttributes( { id: value } );
        };

        return (
            <div>
                <SelectControl
                    label={ __( 'Select a post:', 'plugin-domain' ) }
                    value={ attributes.id }
                    options={ ... fill with all post titles/ids of a specific post type ... }
                    onChange={ setID }
                />
            </div>
        );

    },

    save: props => { ... omitted for brevity ... }

};

registerBlockType( 'my/postselectblock', settings );
0
, , leemon 2 years 2020-01-03T08:38:59-05:00 0 Answers 86 views 0

Leave an answer

Browse
Browse