以前の記事の続きです。今回はWordpress5 Gutenberg のBlockに editor機能を追加して、文字を書いたりできるようにする方法です。

以前の記事はこちら

参考にしたサイトは、ここ「Introducing Attributes and Editable Fields」です。今回は、block.jsのコードの中で、「attributes」をやりとりしているのと、 wp.editor RichTextというタグを持ってきているところがポイント。出来上がるとこんな感じのBlockが使えるようになります。

ファイル構成

前回の「その3」から、index.php, block.jsに変更が入ります。 css ファイルとかは、class名が block名と繋がっているからそこは修正。

index.php

wp_register_scriptのところで、arrayのなかに「’wp-editor’」が追加されていて、block.jsでeditor用の機能を import できるようになっています。

<?php
/**
 * Plugin Name: Gutenberg Examples Editable EsNext
 * Plugin URI: https://github.com/WordPress/gutenberg-examples
 * Description: This is a plugin demonstrating how to register new blocks for the Gutenberg editor.
 * Version: 1.0.2
 * Author: the Gutenberg Team
 *
 * @package gutenberg-examples
 */
defined( 'ABSPATH' ) || exit;
/**
 * Load all translations for our plugin from the MO file.
*/
add_action( 'init', 'gutenberg_examples_03_esnext_load_textdomain' );
function gutenberg_examples_03_esnext_load_textdomain() {
	load_plugin_textdomain( 'gutenberg-examples', false, basename( __DIR__ ) . '/languages' );
}
/**
 * Registers all block assets so that they can be enqueued through Gutenberg in
 * the corresponding context.
 *
 * Passes translations to JavaScript.
 */
function gutenberg_examples_03_esnext_register_block() {
	if ( ! function_exists( 'register_block_type' ) ) {
		// Gutenberg is not active.
		return;
	}
	wp_register_script(
		'gutenberg-examples-03-esnext',
		plugins_url( 'block.build.js', __FILE__ ),
		array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' ),
		filemtime( plugin_dir_path( __FILE__ ) . 'block.build.js' )
	);
	wp_register_style(
		'gutenberg-examples-03-esnext-editor',
		plugins_url( 'editor.css', __FILE__ ),
		array( 'wp-edit-blocks' ),
		filemtime( plugin_dir_path( __FILE__ ) . 'editor.css' )
	);
	wp_register_style(
		'gutenberg-examples-03-esnext',
		plugins_url( 'style.css', __FILE__ ),
		array( ),
		filemtime( plugin_dir_path( __FILE__ ) . 'style.css' )
	);
	register_block_type( 'gutenberg-examples/example-03-editable-esnext', array(
		'style' => 'gutenberg-examples-03-esnext',
		'editor_style' => 'gutenberg-examples-03-esnext-editor',
		'editor_script' => 'gutenberg-examples-03-esnext',
	) );
  if ( function_exists( 'wp_set_script_translations' ) ) {
    /**
     * May be extended to wp_set_script_translations( 'my-handle', 'my-domain',
     * plugin_dir_path( MY_PLUGIN ) . 'languages' ) ). For details see
     * https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/
     */
    wp_set_script_translations( 'gutenberg-examples-03-esnext', 'gutenberg-examples' );
  }
}
add_action( 'init', 'gutenberg_examples_03_esnext_register_block' );

block.js

registerBlockType で「attributes」というのが追加されていて、それが、save, edit の引数(ここだと prop )を通して受け渡しされていく感じです。あとは、wp.editorのRichTextを使うことで、bold、Italicなどが、edit中に選べるようになるのかな。

const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;

registerBlockType( 'gutenberg-examples/example-03-editable-esnext', {
    title: 'Hello World (Step 3)',
    icon: 'universal-access-alt',
    category: 'layout',
    attributes: {
    	content: {
    		type: 'array',
    		source: 'children',
    		selector: 'p',
    	},
    },

    edit: ( props ) => {
    	const { attributes: { content }, setAttributes, className } = props;
    	const onChangeContent = ( newContent ) => {
    		setAttributes( {content: newContent } );
    	};
    	
        return (
	        <RichText
	        	tagName="p"
	        	className={ className }
	        	onChange={ onChangeContent }
	        	value={ content }
	        />
        );
    },

    save: ( props ) => {
        return <RichText.Content tagName="p" value={ props.attributes.content } />;
    }
} );

動作確認

今回もesnextでソースをかいているので、buildしてから試します。

npm install
npm run build

PluginをActivate した後、このBlockが表示されたらOK.



補足: 他のファイル

style.css

.wp-block-gutenberg-examples-example-03-editable-esnext {
	color: darkred;
	background: #fcc;
	border: 2px solid #c99;
	padding: 20px;
}

editor.css

.wp-block-gutenberg-examples-example-03-editable-esnext {
	color: green;
	background: #cfc;
	border: 2px solid #9c9;
	padding: 20px;
}

webpack.config.js

module.exports = {
    entry: './block.js',
    output: {
        path: __dirname,
        filename: 'block.build.js',
    },
    module: {
        loaders: [
            {
                test: /.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
            },
        ],
    },
};

.babelrc

{
     "presets": [
         [ "env", {
             "modules": false,
             "targets": {
                 "browsers": [
                     "last 2 Chrome versions",
                     "last 2 Firefox versions",
                     "last 2 Safari versions",
                     "last 2 iOS versions",
                     "last 1 Android version",
                     "last 1 ChromeAndroid version",
                     "ie 11"
                 ]
             }
         } ]
     ],
     "plugins": [
         [ "transform-react-jsx", {
             "pragma": "wp.element.createElement"
         } ]
     ]
 }

package.json

{
   "name": "01-basic-esnext",
   "version": "1.0.0",
   "license": "GPL-2.0-or-later",
   "main": "block.js",
   "devDependencies": {
     "babel-core": "^6.25.0",
     "babel-loader": "^7.1.1",
     "babel-plugin-transform-react-jsx": "^6.24.1",
     "babel-preset-env": "^1.6.0",
     "cross-env": "^5.0.1",
     "webpack": "^3.1.0"
   },
   "scripts": {
     "build": "cross-env BABEL_ENV=default NODE_ENV=production webpack",
     "dev": "cross-env BABEL_ENV=default webpack --watch"
   }
 }