Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Created November 25, 2024 17:49
Show Gist options
  • Save markhowellsmead/110e965a0abb8fdb03eaf692df64a69d to your computer and use it in GitHub Desktop.
Save markhowellsmead/110e965a0abb8fdb03eaf692df64a69d to your computer and use it in GitHub Desktop.
Add an SVG to the link block link depending on the parent class
import { useEffect } from '@wordpress/element';
import { subscribe } from '@wordpress/data';
import domReady from '@wordpress/dom-ready';
import { registerPlugin } from '@wordpress/plugins';
// Inline SVG
const ArrowSVG = `<svg class="wp-block-button__svg" xmlns="http://www.w3.org/2000/svg" width="91.703" height="55.421" class="o-button-arrow">
<g>
<g class="o-button-arrow__arrow">
<g>
<path fill="none" stroke="currentcolor" stroke-width="1.4" d="m52.318 21.161 6.628 6.6-6.628 6.6"/>
</g>
<g>
<path fill="none" stroke="currentcolor" stroke-width="1.4" d="M0 27.761h59.046"/>
</g>
</g>
<g fill="none">
<path d="m53.249 0 38.452 27.71-38.452 27.71-38.452-27.71Z"/>
<path fill="currentcolor" d="M15.483 27.71 53.25 54.929l37.767-27.217L53.25.494 15.483 27.71m-.684 0L53.249 0l38.453 27.71L53.25 55.42 14.8 27.711Z"/>
</g>
</g>
</svg>`;
// Function to insert SVG directly
const insertSVGToButton = () => {
const buttons = document.querySelectorAll('.wp-block-button');
buttons.forEach((button) => {
const link = button.querySelector('.wp-block-button__link');
if (button.classList.contains('is-style-arrow')) {
// Check if the SVG is already added
if (!link.querySelector('.wp-block-button__svg')) {
// Append the SVG directly
link.insertAdjacentHTML('beforeend', ArrowSVG);
}
} else if (link.querySelector('.wp-block-button__svg')) {
// Remove the SVG if style is not applied
link.querySelector('.wp-block-button__svg').remove();
}
});
};
const ButtonWithArrow = () => {
useEffect(() => {
// Ensure SVG is inserted when the block editor state changes
const unsubscribe = subscribe(() => {
insertSVGToButton();
});
// Run once when the editor initializes
domReady(() => {
insertSVGToButton();
});
// Cleanup subscription on unmount
return () => {
unsubscribe();
};
}, []);
return null;
};
// Register the component to run in the editor
registerPlugin('button-with-arrow', {
render: ButtonWithArrow,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment