Change width of post title in Gutenberg

I wanted a way to tweak the width of post titles to optimize where it breaks to a new line. 

I created the metabox with Advanced Custom Fields using the Range field type. I set the maximum value and default value to the current max-width of the post title, and the minimum to something reasonable.

I then customized my theme to add the max-width CSS if the value is less than 1168px. Since my site is built on Genesis, I leveraged the Markup API by adding this to single.php:

<?php
/**
* Post Title Width
* @see https://www.billerickson.net/change-width-of-post-title-in-gutenberg/
*/
function be_single_post_title_width( $attr ) {
$custom_width = intval( get_post_meta( get_the_ID(), 'ea_post_header_width', true ) );
if( empty( $custom_width ) || 1168 == $custom_width )
return $attr;
$attr['style'] = 'max-width: ' . $custom_width . 'px';
return $attr;
}
add_filter( 'genesis_attr_entry-title', 'be_single_post_title_width' );
view raw single.php hosted with ❤ by GitHub

That works great on the frontend, but I wanted live updating in the Gutenberg editor so I know what size to use before publishing the post. I enqueued the following JavaScript in the Gutenberg editor: 

<?php
/**
* Gutenberg scripts and styles
*
*/
function ea_gutenberg_scripts() {
wp_enqueue_script( 'ea-gutenberg', get_stylesheet_directory_uri() . '/assets/js/gutenberg-min.js', array( 'jquery' ), filemtime( get_stylesheet_directory() . '/assets/js/gutenberg-min.js' ), true );
}
add_action( 'enqueue_block_editor_assets', 'ea_gutenberg_scripts' );
view raw functions.php hosted with ❤ by GitHub
jQuery(function($){
$(window).load(function(){
var field = acf.getField('field_5c194bf2f653d'),
header = $('.editor-post-title__block');
$(header).css('max-width', field.val() + 'px' );
field.on('change', function(e) {
$(header).css('max-width', field.val() + 'px' );
});
});
});
view raw gutenberg.js hosted with ❤ by GitHub

You’ll need to change the field key to match whatever your ACF field is named. This code leverages the ACF JavaScript API.

You also need to make sure your Gutenberg editor styles match the frontend of your site. See my post on Building a Gutenberg website for details.

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk

Reader Interactions

Comments

  1. The video is not working. Earlier today it had a speaker looking icon with a strike-thru. Now it just won’t play. I’ve also had these type of problems using the video block.

    • That’s strange. It works in every browser I test. Maybe you have an adblocker or other browser extension blocking it.

      What browser/OS are you using?

Leave A Reply