Home > other >  Add button styles to wordpress editor?
Add button styles to wordpress editor?

Time:10-24

I am creating a wordpress theme and I want to have some preset button styles to choose from.

In the wordpress editor the button styles are limited to 'Fill' and 'Outline', how do I add my own styles in this list?

I see there is a button/block.json in the core files where it lists the available styles. How do I override this in my theme?

CodePudding user response:

You can do this by exploring the wp.blocks JavaScript API:

Add editor.js in your theme directory with the following contents:

wp.blocks.registerBlockStyle('core/button', {
    name: 'example-button',
    label: 'Example Button Style'
});

Then define your styles via the following CSS class name for the WordPress Admin content editor:

Add editor.css in your theme directory:

.wp-block-button.is-style-example-button .wp-block-button__link {
    background-color: red;
}

Then define your styles via the following CSS class for the public user facing theme:

Add these to your theme CSS files (style.css) the one you output to the user:

.is-style-example-button .wp-block-button__link {
    background-color: red;
}

At the end you need to register your scripts. Add this to your functions.php file:

// Enqueue Block Editor styles
add_action('enqueue_block_editor_assets', 'example_editor_styles');
function example_editor_styles() {
    wp_enqueue_style('example-editor', get_template_directory_uri() . '/editor.css', array('wp-edit-blocks'));
}
// Enqueue Block Editor script
add_action('enqueue_block_editor_assets', 'example_block_enqueues');
function example_block_enqueues() {
    wp_enqueue_script('your-theme-editor-customisations', get_template_directory_uri() . '/editor.js', array('wp-edit-post', 'wp-blocks', 'wp-dom-ready'), '', true);
}
  • Related