Search code examples
wordpresswordpress-themingwordpress-rest-apiwordpress-gutenberg

Gutenberg custom meta blocks not saving meta to custom post type


I have a site with a custom post type set up to define home page call to action boxes.

The title, description, and featured image are all handled by the default blocks/features of the edtior, but I'm trying to add a custom block to save a url to the post's meta.

The block renders properly but it is not saving the meta data, the updateBlockValue function is defintely being called.

I have used almost identical code to create custom meta blocks for pages and posts. Does this method just not work with custom post types?

this is the code I'm using:

PHP

function wb_blocks() {

    wp_register_script(
        'wb-blocks-js',
        get_template_directory_uri() . '/scripts/block.js',
        array( 'wp-blocks', 'wp-editor', 'wp-element','wp-components' )
    );
    register_block_type( 'ray/homebox-link-url', array(
        'editor_script' => 'wb-blocks-js',
    ) );

}
add_action( 'init', 'wb_blocks' );
function wb_register_block_meta() {

    register_meta( 'post', 'homebox_link_url', array(
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string',
    ) );

}

add_action( 'init', 'wb_register_block_meta' );

JS

registerBlockType( 'ray/homebox-link-url', {
title: 'Homebox Link',
icon: 'universal-access-alt',
category: 'layout',
attributes: {
    blockValue: {
        type: 'string',
        source: 'meta',
        meta: 'homebox_link_url',
    }
},

edit: function( props ) {
    var setAttributes = props.setAttributes;

    function updateBlockValue( blockValue ) {
        setAttributes({ blockValue });
    }

    return el(
       'div',
       { className: "homebox-link-url" },
        el( 'h5',{}, 'URL to link to:'),
        el (TextControl,
        {
            onChange: updateBlockValue,
            value: props.attributes. blockValue,
        })
    );
},

save: function( props ) {
     return null;
},
} );

Solution

  • Your block-related code looks fine.

    The issue is probably with the custom post type. When you register it, you have to make sure it supports custom fields:

    register_post_type(
      'post-type',
      [
        // […]
        'supports' => [
          // […]
          'custom-fields',
        ],
      ]
    );
    

    This last step makes sure that your custom post type exposes the meta-property from the REST API, which is what Gutenberg uses to view/update the data.

    Source: https://github.com/WordPress/gutenberg/issues/5622#issuecomment-375362438