Site Announcement Block Managed in Settings
Adds an "Announcement" text field to Settings > General and a block that displays it, so you can place the block on many pages and change the message everywhere from one setting.
Opens WPIDE on
Code
add_action( 'admin_init', function () {
register_setting( 'general', 'wpide_announcement', array(
'type' => 'string',
'sanitize_callback' => 'wp_kses_post',
'default' => '',
) );
add_settings_field( 'wpide_announcement', '<label for="wpide_announcement">Announcement</label>', function () {
printf(
'<textarea id="wpide_announcement" name="wpide_announcement" rows="3" class="large-text">%s</textarea><p class="description">Shown wherever the Announcement block is placed. Leave empty to hide it.</p>',
esc_textarea( (string) get_option( 'wpide_announcement', '' ) )
);
}, 'general' );
} );
add_action( 'init', function () {
wp_register_script( 'wpide-block-announcement', false, array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-server-side-render' ), '1.0', true );
wp_add_inline_script( 'wpide-block-announcement', <<<'JS'
( function ( wp ) {
var el = wp.element.createElement;
wp.blocks.registerBlockType( 'wpide/announcement', {
apiVersion: 3,
title: 'Announcement',
icon: 'megaphone',
category: 'widgets',
edit: function () {
return el( 'div', wp.blockEditor.useBlockProps(),
el( wp.serverSideRender, { block: 'wpide/announcement', EmptyResponsePlaceholder: function () { return el( 'p', null, 'The announcement is empty. Set it in Settings > General.' ); } } )
);
},
save: function () { return null; }
} );
} )( window.wp );
JS
);
register_block_type( 'wpide/announcement', array(
'api_version' => 3,
'title' => 'Announcement',
'category' => 'widgets',
'editor_script_handles' => array( 'wpide-block-announcement' ),
'render_callback' => function () {
$message = trim( (string) get_option( 'wpide_announcement', '' ) );
if ( '' === $message ) {
return '';
}
return '<div ' . get_block_wrapper_attributes( array( 'class' => 'wpide-announcement', 'role' => 'note' ) ) . '>' . wpautop( wp_kses_post( $message ) ) . '</div>';
},
) );
} );
Notes
The block outputs nothing while the setting is empty, so you can leave it in place between announcements.
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.