Skip to content

Instantly share code, notes, and snippets.

@wpmark
Last active January 4, 2023 07:50
Show Gist options
  • Save wpmark/796b301847c45884f10c014ce8d61a57 to your computer and use it in GitHub Desktop.
Save wpmark/796b301847c45884f10c014ce8d61a57 to your computer and use it in GitHub Desktop.
Add alignment options for WordPress core blocks.

WordPress block support for alignment options

If you are looking to add alignment options to some core blocks that don't support alignment, this is the way to achieve it. Add the javascript here to a file in the following location in your active theme:

assets/js/editor.js

and enqueue it in your themes functions.php file like so:

/**
 * Enqueue the correct scripts for the Gutenberg block editor.
 */
function hd_gutenberg_scripts() {

	// enqueue the editor js for the starter theme/
	wp_enqueue_script(
		'hd_editor',
		get_stylesheet_directory_uri() . '/assets/js/editor.js',
		array(
			'wp-blocks',
			'wp-dom'
		),
		filemtime( get_stylesheet_directory() . '/assets/js/editor.js' ),
		true
	);

}

add_action( 'enqueue_block_editor_assets', 'hd_gutenberg_scripts' );
// set alignment options for cover, video, and paragraph blocks.
wp.hooks.addFilter(
'blocks.registerBlockType',
'hd-theme/hd-theme',
function( settings, name ) {
if ( name === 'core/cover' || name === 'core/video' || name === 'core/paragraph' || name === 'core/list' ) {
return lodash.assign( {}, settings, {
supports: lodash.assign( {}, settings.supports, {
// allow support for full and wide alignment.
align: ['full', 'wide'],
} ),
} );
}
return settings;
}
);
@markhowellsmead
Copy link

Great! A possible simplification:

// set alignment options for cover, video, and paragraph blocks.
wp.hooks.addFilter(
    'blocks.registerBlockType',
    'hd-theme/hd-theme',
    function( settings, name ) {
        let supported_blocks = [
            'core/cover',
            'core/paragraph',
            'core/list',
        ];
        if ( supported_blocks.includes(name) ) {
            return lodash.assign( {}, settings, {
                supports: lodash.assign( {}, settings.supports, {
                    // allow support for full and wide alignment.
                    align: ['full', 'wide'], 
                } ),
            } );
        }
        return settings;
    }
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment