How to add a custom H1 title to a tag page

By default wordpress writes an H1 with the tag term, which can be very limited in terms of SEO. For instance, you may have a tag page title “USA” instead of “News from the United States of America” if your tag is only “USA”. To improve that without any plugin, open your theme’s functions.php file and add the following lines :


/*
CUSTOM H1 TITLES FOR TAGS PAGES by Ghyslain 3 mai 2023
*/

function add_custom_h1_title_field( $term ) {
$term_id = $term->term_id;
$custom_h1_title = '';
if ( isset( $_POST['custom_h1_title'] ) ) {
$custom_h1_title = sanitize_text_field( $_POST['custom_h1_title'] );
} elseif ( $term_id ) {
$custom_h1_title = get_term_meta( $term_id, 'custom_h1_title', true );
}
?>
<div class="form-field term-group">
<label for="custom_h1_title"><?php _e( 'Custom H1 title', 'text-domain' ); ?></label>
<input type="text" class="form-field" name="custom_h1_title" id="custom_h1_title" value="<?php echo esc_attr( $custom_h1_title ); ?>">
</div>
<?php
}

add_action( 'post_tag_edit_form_fields', 'add_custom_h1_title_field' );
add_action( 'product_tag_add_form_fields', 'add_custom_h1_title_field' );

function save_custom_h1_title_field( $term_id ) {
if ( isset( $_POST['custom_h1_title'] ) ) {
update_term_meta( $term_id, 'custom_h1_title', sanitize_text_field( $_POST['custom_h1_title'] ) );
}
}
add_action( 'edited_post_tag', 'save_custom_h1_title_field' );
add_action( 'created_post_tag', 'save_custom_h1_title_field' );

You will get a new text field in your admin edit screen called “Custom H1 title”.
Now in your theme’s tag.php file, replace the lines where the H1 was being called by :

$custom_h1_title = get_term_meta(get_queried_object_id(), 'custom_h1_title', true);
if ($custom_h1_title) {
echo esc_html($custom_h1_title);
} else {
single_tag_title();
}