Archived topic
Conditional Page Title or Page Header
3 replies · Started by Donnie on November 2, 2018
I am working to build a GeneratePress Header Element with a conditional page title.
Using Advanced Custom Fields, I have created a custom field named "page_headline"
By default, I would like to display the regular WordPress page title. However, if a value is entered for "page_headline" I would like to display it instead.
I've attempted to accomplish this two ways. The first was by defining a shortcode that I entered into the GeneratePress Header Element. Although I could get the conditional logic to work, the shortcode displayed outside the page-hero area. More specifically, the shortcode displayed between the "header-wrap" div and the "page-hero" div. The code I used for that shortcode is as follows:
function dg_conditional_page_header() {
if ( get_field('page_headline') ) {
// Display ACF Page Title Override
echo '<h1>' . get_field('page_headline') . '</h1>';
}
else {
// Display Page Title if no value set for "page_headline"
echo '<h1>' . get_the_title( ) . '</h1>';
}
if ( get_field('page_teaser') ) {
echo '<p>' . get_field('page_teaser') . '</p>';
}
}
add_shortcode( 'dg_page_header', 'dg_conditional_page_header' );
With the above code displaying outside the page-hero div, I turned to attempting with a Hook placed at wp_head. The code I used for the hook (which didn't work) was as follows:
if ( get_field('page_headline') ) {
// Set PHP $headline variable to ACF "page_headline" field value
$headline = get_field('page_headline');
apply_filters( 'the_title', $headline );
}
Nonetheless, any help or insights into what I'm overlooking are greatly appreciated.
Thanks in advance.
Hi there
Shortcodes are funny in that they need the content to be returned instead of echoed.
Try this:
function dg_conditional_page_header() {
ob_start();
if ( get_field('page_headline') ) {
// Display ACF Page Title Override
echo '<h1>' . get_field('page_headline') . '</h1>';
}
else {
// Display Page Title if no value set for "page_headline"
echo '<h1>' . get_the_title( ) . '</h1>';
}
if ( get_field('page_teaser') ) {
echo '<p>' . get_field('page_teaser') . '</p>';
}
return ob_get_clean();
}
add_shortcode( 'dg_page_header', 'dg_conditional_page_header' );
Thanks for your help. That did the trick.
Awesome, glad I could help :)