Search Result Preview in the Block Editor
Adds a panel to the editor sidebar that previews how the post may look as a search engine result, with its title, address and description, updating live as you edit the title and excerpt.
Opens WPIDE on
Code
add_action( 'enqueue_block_editor_assets', function () {
$screen = get_current_screen();
if ( ! $screen || 'post' !== $screen->base ) {
return;
}
wp_register_script( 'wpide-serp-preview', false, array( 'wp-plugins', 'wp-element', 'wp-data', 'wp-editor' ), '1.0', true );
wp_enqueue_script( 'wpide-serp-preview' );
wp_add_inline_script( 'wpide-serp-preview', 'var wpideSerp = ' . wp_json_encode( array( 'site' => get_bloginfo( 'name' ), 'home' => home_url( '/' ) ) ) . ';' . <<<'JS'
( function ( wp ) {
var el = wp.element.createElement;
var Panel = ( wp.editor && wp.editor.PluginDocumentSettingPanel ) || ( wp.editPost && wp.editPost.PluginDocumentSettingPanel );
if ( ! Panel ) { return; }
function clip( text, max ) { return text.length > max ? text.slice( 0, max - 1 ).replace( /\s+\S*$/, '' ) + '…' : text; }
function SerpPreview() {
var data = wp.data.useSelect( function ( select ) {
var editor = select( 'core/editor' );
return {
title: editor.getEditedPostAttribute( 'title' ) || '',
excerpt: editor.getEditedPostAttribute( 'excerpt' ) || '',
content: editor.getEditedPostAttribute( 'content' ) || '',
link: editor.getPermalink() || wpideSerp.home
};
}, [] );
var text = ( data.excerpt || data.content ).replace( /<[^>]+>/g, ' ' ).replace( /\s+/g, ' ' ).trim();
var url = data.link.replace( /^https?:\/\//, '' ).replace( /\/$/, '' ).split( '/' ).join( ' › ' );
return el( Panel, { name: 'wpide-serp-preview', title: 'Search result preview' },
el( 'div', { style: { fontFamily: 'arial, sans-serif', lineHeight: 1.4 } },
el( 'div', { style: { fontSize: '12px', color: '#4d5156' } }, wpideSerp.site + ' · ' + url ),
el( 'div', { style: { fontSize: '17px', color: '#1a0dab', margin: '2px 0' } }, clip( ( data.title || '(no title)' ) + ' - ' + wpideSerp.site, 62 ) ),
el( 'div', { style: { fontSize: '13px', color: '#4d5156' } }, clip( text || 'Add an excerpt to control this text.', 158 ) )
)
);
}
wp.plugins.registerPlugin( 'wpide-serp-preview', { render: SerpPreview } );
} )( window.wp );
JS
);
} );
Notes
Uses the excerpt (or the opening text) as the description; SEO plugins with their own preview may make this redundant.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.