Last active
October 25, 2023 09:04
-
-
Save RadGH/c5ef944edf39265788cabe5c77b918cb to your computer and use it in GitHub Desktop.
WordPress Block Editor - Custom SVG icon using javascript filter
This file contains hidden or 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
// Result: https://radleysustaire.com/s3/d87fe5/chrome | |
// Enqueue this script in PHP during the action "enqueue_block_editor_assets": | |
// $deps = array('wp-element', 'wp-hooks'); | |
// wp_register_script( 'rs-download-block-editor', RSD_URL . '/assets/block-editor.js', $deps ); | |
// This filter replaces the icon of any block with the prefix "rs-downloads/" using a custom SVG icon | |
wp.hooks.addFilter( | |
'blocks.registerBlockType', | |
'rs-downloads/modify_icon', | |
function(settings, name) { | |
// Change the icon of all "RS Downloads" blocks (plugin prefix) | |
if ( name.indexOf('rs-downloads/') !== 0 ) return settings; | |
// Path string containing the entire icon in one path. Also see assets/icon.svg | |
const path_string = "M2.47 1.3a2 2 0 0 0-2 2v7.5c0 1.11.9 2 2 2H8.4v1.77H3.5l8.59 8.85 8.58-8.85h-4.9V12.8h5.77a2 2 0 0 0 2-2V3.3a2 2 0 0 0-2-2zm9.88 1.99c.54 0 1.02.1 1.44.28.43.2.76.47 1 .83.24.35.36.75.36 1.21h-1.8a.9.9 0 0 0-.29-.7 1.08 1.08 0 0 0-.75-.26c-.32 0-.58.07-.77.21a.65.65 0 0 0-.27.54c0 .2.1.37.3.53a4 4 0 0 0 1.09.48c.52.17.94.34 1.27.54.81.46 1.22 1.1 1.22 1.92 0 .66-.25 1.17-.74 1.55a3.3 3.3 0 0 1-2.04.56c-.6 0-1.15-.11-1.65-.33a2.52 2.52 0 0 1-1.1-.9 2.35 2.35 0 0 1-.38-1.3h1.81c0 .4.1.7.31.89.21.19.55.28 1.02.28.3 0 .53-.06.7-.2a.64.64 0 0 0 .26-.54c0-.26-.1-.46-.28-.61-.19-.15-.51-.3-.98-.46a9.43 9.43 0 0 1-1.15-.46c-.97-.47-1.46-1.13-1.46-1.96 0-.42.12-.78.36-1.1.24-.31.59-.56 1.03-.74.44-.17.94-.26 1.49-.26zm-9.74.1h2.95c.89 0 1.58.2 2.08.59.5.4.75.95.75 1.67 0 .52-.1.95-.32 1.3-.2.34-.54.62-.98.83l1.56 3.02v.07H6.7L5.4 8.23h-.97v2.64h-1.8Zm13.46 0h2.41c.66 0 1.26.15 1.79.45.52.3.94.72 1.23 1.27.3.55.45 1.16.45 1.84v.34c0 .69-.14 1.3-.43 1.85-.3.54-.7.96-1.23 1.27-.52.3-1.1.46-1.76.46h-2.46ZM4.42 4.79v2.05h1.14c.34 0 .6-.1.77-.27.17-.18.26-.43.26-.75 0-.33-.09-.58-.26-.76-.17-.19-.43-.28-.77-.28Zm13.46 0v4.7h.62c.52 0 .92-.19 1.2-.55.27-.37.41-.92.41-1.65v-.32c0-.73-.14-1.27-.41-1.64a1.43 1.43 0 0 0-1.22-.55z"; | |
// Create an SVG icon for the block | |
// Note: If your SVG has multiple paths, replace the last arg with an array of multiple path elements. | |
// Note: Also consider using wp.primitives.SVG and wp.primitives.Path instead of createElement. | |
settings.icon = wp.element.createElement('svg', {}, [ wp.element.createElement('path', { key: 0, d: path_string }) ]); | |
return settings; | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result:
