Search code examples
javascriptphpwordpresswordpress-gutenberggutenberg-blocks

Display list of custom post type in Wordpress Gutenberg custom block


I'm trying to enable users of my Wordpress plugin/theme, which uses a custom post type to handle products, to make a block that displays a summary of one of these custom posts. I'm trying to accomplish this by creating a custom block in my plugin, based on the official tutorial. On the Gutenberg backend I'd like to simply display a select box with all the custom posts as options, but I'm open to suggestions.

I have tried to read up on what I can pass to the getEntityRecords function in the block's javascript file, but documentation seems really sparse. If someone could point me in the right direction, I'd really appreciate it. I have also tried to set 'taxonomy' instead of 'postType', but it did not work either. Without good API docs, possible options and parameters are hard to guess.

Here is (part of) my code. I'd like to know the possible parameters for getEntityRecords in line 3.

edit: withSelect( function( select ) {
    // setting postType to 'product' does not work for me here
    var pages = select('core').getEntityRecords('postType', 'page', { per_page: 10 });
    return {
        posts: pages
    };
} )( function( props ) {
    if ( ! props.posts ) {
        return "Loading...";
    }

    if ( props.posts.length === 0 ) {
        return "No posts";
    }
    var className = props.className;
    var post = props.posts[ 0 ];

    var options = [];
    for (var i = 0; i < props.posts.length; i++) {
        var option = el(
            'option',
            { value: props.posts[i].id },
            props.posts[i].title.rendered
        );
        options.push(option);
    }

    var select = el(
        'select',
        { className: className },
        options
    );

    return select;
} ),

Solution

  • If you're having the same issue I was: When declaring the custom post type you have to have 'show_in_rest' => true, since the blocks are based on the restAPI;) Hope this helps