Last active
May 19, 2023 18:14
-
-
Save sinanisler/8a1587bd503925ac7ad320a33c1dbe19 to your computer and use it in GitHub Desktop.
simple wordpress block native .js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// put this .js on your theme /blocks/ folder name it your-block.js | |
(function () { | |
var registerBlockType = wp.blocks.registerBlockType; | |
var RichText = wp.blockEditor.RichText; | |
registerBlockType('your-theme/block', { | |
title: 'Your Block', | |
description: 'Add a title and description', | |
icon: 'smiley', | |
category: 'common', | |
attributes: { | |
title: { | |
type: 'string', | |
source: 'html', | |
selector: 'h2', | |
}, | |
description: { | |
type: 'string', | |
source: 'html', | |
selector: 'p', | |
}, | |
}, | |
edit: function (props) { | |
var blockProps = wp.blockEditor.useBlockProps(); | |
var onChangeTitle = function (newTitle) { | |
props.setAttributes({ title: newTitle }); | |
}; | |
var onChangeDescription = function (newDescription) { | |
props.setAttributes({ description: newDescription }); | |
}; | |
return wp.element.createElement( | |
'div', | |
blockProps, | |
wp.element.createElement( | |
RichText, | |
{ | |
tagName: 'h2', | |
placeholder: 'Enter a title', | |
value: props.attributes.title, | |
onChange: onChangeTitle, | |
} | |
), | |
wp.element.createElement( | |
RichText, | |
{ | |
tagName: 'p', | |
placeholder: 'Enter a description', | |
value: props.attributes.description, | |
onChange: onChangeDescription, | |
} | |
) | |
); | |
}, | |
save: function (props) { | |
var blockProps = wp.blockEditor.useBlockProps.save(); | |
return wp.element.createElement( | |
'div', | |
blockProps, | |
wp.element.createElement('h2', null, props.attributes.title), | |
wp.element.createElement('p', null, props.attributes.description) | |
); | |
}, | |
}); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// this is how you register your simple block on theme fucntions.php | |
function your_theme_enqueue_block_editor_assets() { | |
wp_enqueue_script( | |
'your-block', | |
get_template_directory_uri() . '/blocks/your-block.js', | |
array( 'wp-blocks', 'wp-block-editor', 'wp-element' ), | |
filemtime( get_template_directory() . '/blocks/your-block.js' ) | |
); | |
} | |
add_action( 'enqueue_block_editor_assets', 'your_theme_enqueue_block_editor_assets' ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment