Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Created February 10, 2018 19:24
Show Gist options
  • Save Shelob9/36d7096d919995ae615d4d4bbf10ffbc to your computer and use it in GitHub Desktop.
Save Shelob9/36d7096d919995ae615d4d4bbf10ffbc to your computer and use it in GitHub Desktop.
(function (wp) {
//WordPress APIs
//Render function
var el = wp.element.createElement;
//Translations
var __ = wp.i18n.__;
//Text input control
var TextControl = wp.blocks.InspectorControls.TextControl;
//Create block
wp.blocks.registerBlockType('shelob9/metatest2', {
title: __('Meta 2 and Markup', 'metatest'),
category: 'common',
edit: function (props) {
//Make sure "fake_content" and "content" are in sync
if( props.attributes.fake_content !== props.attributes.content ){
props.setAttributes({fake_content: props.attributes.content });
}
//Edit interface
return el(
'div',
{
},
[
el(
'p',
{
className: props.className
},
props.attributes.content
),
el(
TextControl,
{
label: __('Content', 'metatest'),
value: props.attributes.fake_content,
onChange: function (value) {
//Update both attributes
props.setAttributes({
fake_content: value,
content: value
});
}
},
)
]
)
},
save: function (props) {
return el(
'p',
{className: props.className},
//Save the non-meta attribute
props.attributes.fake_content
);
}
});
})(
window.wp
);
<?php
function metatest_enqueue_block_editor_assets() {
$dir = dirname( __FILE__ );
$block_js = 'metatest/block.js';
$editor_css = 'metatest/editor.css';
wp_enqueue_script( 'metatest-block', plugins_url( $block_js, __FILE__ ), array(
'wp-blocks',
'wp-i18n',
'wp-element',
), filemtime( "$dir/$block_js" ) );
wp_enqueue_style( 'metatest-block', plugins_url( $editor_css, __FILE__ ), array(
'wp-blocks',
), filemtime( "$dir/$editor_css" ) );
}
add_action( 'enqueue_block_editor_assets', 'metatest_enqueue_block_editor_assets' );
add_action( 'init', function(){
register_block_type( 'shelob9/metatest2', array(
'attributes' => array(
//Meta attribute to use for post meta
'content' => array(
'type' => 'string',
'source' => 'meta',
'meta' => 'metatest_content'
),
//Non-meta attribute to use for post content
'fake_content' => array(
'type' => 'string',
'source' => 'html',
'selector' => 'p'
),
)
));
register_meta( 'post', 'metatest_content', array(
'show_in_rest' => true
));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment