0

I'm using ACF to display a class within a <header> tag. The code for this sits within header.php. The custom field appears across all page templates in WP admin. Here's how it's working on the front-end:

<header 
    class="site-header 
    <?php
        $header = get_field( 'header',$post->ID );
        if ($header) { 
            echo esc_attr( $header ); 
        } 
        else { 
            echo 'white';
        }
    ?>" 
>

This works perfectly on all pages apart from the 404. I'm receiving the following message within dev tools:

<header class="site-header <br /> <b>Notice</b>: Trying to get property of non-object in <b>/Applications/MAMP/htdocs/theme/wp-content/themes/theme/header.php</b> on line <b>28</b><br /> white">
</header>

This is happening because the 404 is a static page / post and does not have an ID associated to it.

Is there a function within WordPress I can use to display my custom field properly?

4
  • You get a 404 if there is no $post.
    – fuxia
    Mar 24 '17 at 11:04
  • Makes sense. Is there a parameter I can pass for non posts?
    – Sam
    Mar 24 '17 at 11:11
  • I don't know. get_field() is not a WordPress function. Ask the ACF support.
    – fuxia
    Mar 24 '17 at 11:12
  • I've edited my question and have found a solution. Thanks for your help.
    – Sam
    Mar 24 '17 at 11:50
1

You should not hide functionality in a template file. Templates are dumb, you don't run unit tests on them normally.

I'd recommend to move the logic to a separate function in your functions.php:

function header_class( $default= 'white' )
{
    $post = get_post();

    // 404 pages, empty archives (user, taxonomy, date)
    if ( empty( $post ) )
        return $default;

    $header = get_field( 'header', $post->ID );

    if ( empty( $header ) || ! is_scalar( $header ) )
        return $default;

    return esc_attr( $header );
}

And in your template you can now just call the function:

<header id="masthead" class="site-header <?= header_class() ?>" role="banner">
1
  • Nice solution, thanks. I'll start using this for future projects.
    – Sam
    Mar 24 '17 at 19:17
1

You can use the is 404 function to resolve this issue. The following worked for me:

<header id="masthead" class="site-header 

    <?php

        if ( is_404() ) {
            echo 'white';
        }

        else {

            $header = get_field( 'header',$post->ID );

            if ( $header ) { 
                echo esc_attr( $header ); 

            } 

            else { 
                echo 'white';
            }
        }

    ?>"

role="banner">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.