The thing you’re talking about is called a custom meta box. They can be used to save post specific settings and data. You can create your own meta boxes with the help of add_meta_box()
function.
Here’s a quick example. This would go to your (child) theme’s functions.php
file. Alternatively if you want to make the code theme independent, then create a custom plugin for the code below. The example works in both Classic and Block editors.
// Register metabox only for "post" post type
add_action('add_meta_boxes_post', 'my_prefix_register_my_custom_metabox', 10, 1);
function my_prefix_register_my_custom_metabox( $post ) {
add_meta_box(
'my-metabox', // id
esc_html__( 'My Meta Box', 'textdomain' ), // title
'my_prefix_render_my_custom_metabox', // callback
'post', // screen - typically post type
'side', // context - normal, side, advanced
'high', // priority - high, low
array() // optional callback args
);
}
// Callback function that add_meta_box uses to render the contents of the metabox
function my_prefix_render_my_custom_metabox( $post, $callback_args ) {
$checked = get_post_meta( $post->ID, '_my_checkbox_value', true );
wp_nonce_field( 'my_custom_metabox_nonce_action_' . $post->ID, 'my_custom_metabox_nonce' );
?>
<label>
<input type="checkbox" name="_my_checkbox_value" value="1" <?php checked( $checked, 1); ?>>
<span><?php esc_html_e( 'Display disclaimer', 'textdomain' ); ?></span>
</label>
<?php
}
// Callback for saving the metabox form fields when the post is saved
// Executes only when saving "post" post type
add_action( 'save_post_post', 'my_prefix_save_my_custom_metabox', 10, 3 );
function my_prefix_save_my_custom_metabox( $post_id, $post, $update ) {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if (
wp_is_post_autosave( $post_id ) ||
wp_is_post_revision( $post_id )
) {
return;
}
if (
empty( $_POST['my_custom_metabox_nonce'] ) ||
! wp_verify_nonce( $_POST['my_custom_metabox_nonce'], 'my_custom_metabox_nonce_action_' . $post_id )
) {
return;
}
if ( isset( $_POST['_my_checkbox_value'] ) ) {
update_post_meta( $post_id, '_my_checkbox_value', 1 );
} else {
delete_post_meta( $post_id, '_my_checkbox_value', 1 );
}
}
You can also add to the same file a helper function which takes care of displaying the disclaimer message.
function my_prefix_display_disclaimer() {
if (
is_single() &&
get_post_meta( get_the_ID(), '_my_checkbox_value', true )
) {
?>
<aside class="disclaimer">
<p>This is a disclaimer.</p>
</aside>
<?php
}
}
You can then either use the helper function directly in some (child) theme template file.
<?php my_prefix_display_disclaimer(); ?>
Or hook it into an action hook that your theme might provide.
// in functions.php or custom plugin file
add_action( 'some_theme_template_action_hook', 'my_prefix_display_disclaimer' );