Archived topic
Replace header post title with custom field
11 replies · Started by Todd on February 3, 2020
Hello, I can see how to get a custom field to show up in a header. But is there a simple way to have a custom field IF present replace the post title? So the post title is the default if there is no custom field populated on a page. If there is a custom field populated then it replaces the title.
Hi there,
Try this:
add_filter( 'generate_page_hero_post_title', function( $title ) {
$custom_field = get_post_meta( get_the_ID(), 'your_custom_field', true );
if ( $custom_field ) {
return $custom_field;
}
return $title;
} );
Let me know :)
Tom, I put a preview test link in the original Support topic.
It seems to show the custom field twice? I assume that I am replacing the 'your_custom_field' with my field name in the snippet so it looks like this:
add_filter( 'generate_page_hero_post_title', function( $title ) {
$custom_field = get_post_meta( get_the_ID(), 'head_pg_header', true );
if ( $custom_field ) {
return $custom_field;
}
return $title;
} );
The header title looks like this:
<h1>{{post_title}}</h1>
<h1>{{custom_field.head_pg_header}}<h1>
You only need this in the header now:
<h1>{{post_title}}</h1>
Worked perfectly. Best customer service in the world!
Awesome! Glad I could help :)
I noticed one other thing I would like to fix with this header solution, if I could. It seems that if there is a page that can not be found or a search with no result or a search with a result, the custom field variable that I have for a subhead shows in the header shows up.
https://customairco.com/qwiktest-03/
https://customairco.com/?s=monkey
https://customairco.com/?s=rheem
It does not show on regular page through out the rest of the site:
https://customairco.com/rheem-hvac-spring-2020-offer/
Thank you.
Custom fields are only available on singular pages/posts.
It would be better to create a separate Element for archives (including search results) without the custom field.
I duplicated the header and made the change. Works well on search and 404 templates. Just curious when this is run on an archive it works well but seems to pick up the title of the first page like you see on the first search example for "Rheem", all the other examples seem fine.
The header is: <h1>{{post_title}}</h1>
We may have to directly target search results to change what {{post_title}} outputs. I'll look into this for GPP 1.10.
Thanks Tom, appreciate it.
No problem! Appreciate the heads up :)