Subtitle Field for Posts
Adds a "Subtitle" box to the post editor, saves it securely and provides a [wpide_subtitle] shortcode and a helper to display it in your theme.
Opens WPIDE on
Code
add_action( 'add_meta_boxes', function () {
add_meta_box( 'wpide-subtitle', 'Subtitle', function ( $post ) {
wp_nonce_field( 'wpide_subtitle_save', 'wpide_subtitle_nonce' );
printf( '<input type="text" class="widefat" name="wpide_subtitle" value="%s" placeholder="Optional subtitle">', esc_attr( get_post_meta( $post->ID, '_wpide_subtitle', true ) ) );
}, 'post', 'side', 'high' );
} );
add_action( 'save_post_post', function ( $post_id ) {
if ( ! isset( $_POST['wpide_subtitle_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_subtitle_nonce'] ), 'wpide_subtitle_save' ) ) {
return;
}
if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$value = isset( $_POST['wpide_subtitle'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_subtitle'] ) ) : '';
if ( '' === $value ) {
delete_post_meta( $post_id, '_wpide_subtitle' );
} else {
update_post_meta( $post_id, '_wpide_subtitle', $value );
}
} );
add_shortcode( 'wpide_subtitle', function () {
$subtitle = get_post_meta( get_the_ID(), '_wpide_subtitle', true );
return $subtitle ? '<p class="wpide-subtitle">' . esc_html( $subtitle ) . '</p>' : '';
} );
Notes
In a classic theme you can print it with echo esc_html( get_post_meta( get_the_ID(), '_wpide_subtitle', true ) );
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.