古腾堡自定义元阻止不将元保存到自定义帖子类型

Whe*_*eak 1 wordpress wordpress-theming wordpress-rest-api wordpress-gutenberg

我有一个设置自定义帖子类型的网站,用于定义主页号召性用语框。

标题、描述和特色图片都由编辑器的默认块/功能处理,但我正在尝试添加一个自定义块以将 url 保存到帖子的元数据中。

该块正确呈现,但未保存元数据,该updateBlockValue函数肯定会被调用。

我使用几乎相同的代码为页面和帖子创建自定义元块。这种方法是否不适用于自定义帖子类型?

这是我正在使用的代码:

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' );
Run Code Online (Sandbox Code Playgroud)

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;
},
} );
Run Code Online (Sandbox Code Playgroud)

Phi*_*mes 5

您的块相关代码看起来不错。

问题可能与自定义帖子类型有关。注册时,您必须确保它支持自定义字段:

register_post_type(
  'post-type',
  [
    // options...
    'supports' => [
      // ...
      'custom-fields',
    ],
  ]
);
Run Code Online (Sandbox Code Playgroud)

最后一步确保您的自定义帖子类型从 REST API 公开元属性,这是古腾堡用来查看/更新数据的。

(摘自https://github.com/WordPress/gutenberg/issues/5622#issuecomment-375362438