Archived topic
Replace H1 (post title) by ACF field (is set)
7 replies · Started by Fabien on September 28, 2021
Hi,
I am looking for a PHP function to replace a single post title by an ACF fied (if set). Can you please help ?
Thanks
Hi Fabien,
You can try the_title filter to modify the title:
Example:
add_filter('the_title', function( $output ){
$acf_field = get_field('your_acf_slug');
if( $acf_field ){
$output = $acf_field;
}
return $output;
});
Thanks @Elvin.
It works but it replaces the title everywhere (see attached screenshot).
Here is the function I've used :
add_filter('the_title', function( $output ){
$custom_title = get_field('custom_title');
if ( is_singular('customcpt') ) {
if ( $custom_title = get_field( 'custom_title' )) {
$output = $custom_title;
}
}
return $output;
});
Try this one:
add_filter('the_title', function( $output ){
$custom_title = get_field('custom_title');
if ( get_post_type( get_the_ID() ) == 'customcpt' ) {
if ( !empty($custom_title) ) {
$output = $custom_title;
}
}
return $output;
});
This code checks if the post type of the current post's post type is 'customcpt' and checks if the ACF field is NOT empty. I've added the not empty condition so the fallback is the default title. :)
Same issue...
Try this method:
function db_custom_field_title( $title ) {
global $id, $post;
if ( $id && $post && $post->post_type == 'customcpt' ) {
$custom_title = get_field('custom_title');
if (!empty($custom_title)) {
$title = $custom_title;
}
}
return $title;
}
add_filter( 'the_title', 'db_custom_field_title' );
Same issue :-(
Thats odd as the filter should only be specific to the post content using that method. Its worked for me :)
Can you share a link to the site where we can see the requirement to change the title?