Skip to content

Instantly share code, notes, and snippets.

@aduth
Forked from pento/stars-block.js
Last active July 12, 2019 18:58
Show Gist options
  • Save aduth/e44d104996277dd9d6b08edf403030c5 to your computer and use it in GitHub Desktop.
Save aduth/e44d104996277dd9d6b08edf403030c5 to your computer and use it in GitHub Desktop.
Gutenberg Stars Block
( function( blocks, element ) {
var el = element.createElement;
function Stars( { stars } ) {
return el( 'div', { key: 'stars' },
'★'.repeat( stars ),
( ( stars * 2 ) % 2 ) ? '½' : '' );
}
blocks.registerBlockType( 'stars/stars-block', {
title: 'Stars Block',
icon: 'format-image',
category: 'common',
attributes: {
stars: {
type: 'int',
source: 'meta', // Store the value in postmeta
meta: 'stars',
}
},
edit: function( props ) {
var stars = props.attributes.stars,
children = [];
function setStars( event ) {
props.setAttributes( { stars: event.target.value } );
event.preventDefault();
}
if ( stars ) {
children.push( Stars( { stars: stars } ) );
}
children.push(
el( 'input', {
key: 'stars-input',
type: 'number',
min: 0,
max: 5,
step: 0.5,
value: stars,
onChange: setStars } )
);
return el( 'form', { onSubmit: setStars }, children );
},
save: function( props ) {
return el( Stars, { stars: props.attributes.stars } );
}
} );
} )(
window.wp.blocks,
window.wp.element
);
<?php
/*
* Plugin Name: Stars Block
* Version: 0.2
* Author: Gary Pendergast
* Author URI: https://pento.net/
* License: GPL3+
*
* Description: Everyone loves stars! Let's add stars (now with more meta)!
*/
function stars_block_init() {
wp_register_script(
'stars-block',
plugins_url( 'stars-block.js', __FILE__ ),
array( 'wp-blocks' )
);
register_block_type( 'stars/stars-block', array(
'editor_script' => 'stars-block',
) );
// Register the postmeta key that we'll store our data in
register_meta( 'post', 'stars', array(
'show_in_rest' => true,
'single' => true,
'type' => 'number',
) );
}
add_action( 'init', 'stars_block_init' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment