Skip to content

Instantly share code, notes, and snippets.

@BinaryMoon
Created February 24, 2021 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BinaryMoon/279f3b163c2dbacacfcfecfdc7545350 to your computer and use it in GitHub Desktop.
Save BinaryMoon/279f3b163c2dbacacfcfecfdc7545350 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Gutenberg Image Alignment
* Plugin URI: https://prothemedesign.com
* Description: Fix image alignment classes in Gutenberg.
* Author: Ben Gillbanks
* Version: 1.0
* Author URI: https://prothemedesign.com
*
* @package ptd
*/
/**
* Move the align* class from the figure to the wrapper in the image block.
*
* @param string $block_content The block html.
* @param array $block Information about the block being rendered.
* @return string
*/
function ptd_gb_move_image_align( $block_content, $block ) {
// Quit if this is not an image block.
if ( 'core/image' !== $block['blockName'] ) {
return $block_content;
}
// The classes we want to move.
$classes = array( 'alignleft', 'alignright', 'aligncenter' );
foreach( $classes as $className ) {
// If the block contains one of the classes then move it around.
if ( false !== strpos( $block_content, $className ) ) {
// Remove the existing class name.
$block_content = str_replace( $className, '', $block_content );
// Add the classname back on the wrapper.
$block_content = str_replace( 'wp-block-image', 'wp-block-image ' . $className, $block_content );
/**
* Remove any empty classes that may have been created.
* Not essential but nice to do.
*/
$block_content = str_replace( 'class=""', '', $block_content );
}
}
return $block_content;
}
add_filter( 'render_block', 'ptd_gb_move_image_align', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment