December 18, 2015 by Antti Koskenrouta

Have you ever wanted to give your page or post a different H1 title from the actual post title? I know I have. Last time I encountered this was while working on MemberPress membership names. What looked good on a page didn’t look good as the product name in Stripe checkout.

How to override the original post title?

In WP Admin, the easiest way to achieve this is to use Advanced Custom Fields plugin; Just create a new field group, add a text field to it and set it to appear for the desired content types.

WP_ACF_Alternative_title

But how to make the title appear on the front end? You could do if-else statements in your page templates, for example, but this can get cumbersome. The most straightforward way is to use the the_title filter. See the function below:

function override_h1($title, $id){
return ( '' != get_post_meta( $id, 'alternative_title', true ) ) ? esc_html( get_post_meta( $id, 'alternative_title', true ) ) : $title;
}
add_filter( 'the_title', 'override_h1', 20, 2 );

We have created a simple function that accepts two arguments: the original title and the post ID. The function takes the post’s ID and attempts to retrieve the alternative title form the postmeta table. If one exists, it replaces the original title. If the alternative title doesn’t exist or is empty, the original title is replaced.

Additional tests can be added before this logic if you want the test to run on specific pages or post types, for example.

How to deploy this title override?

The easiest way to use this function is to add it into your theme’s functions.php file. A more sophisticated and self-contained way would be to wrap it into a plugin.

 

 

Categories: Tutorials