The values of custom fields are not available functions.php

This is because you’re doing it too early. You need to wrap your code in the necessary hook so that it occurs at the correct time.

Because you don’t tell get_field the ID of the current post, it needs to know which post to get the field from, and it does this by referencing the global variable $post, which gets set when you call the_post, or by WP Core early on during a page load.

But if you try to do this before it’s set, the function doesn’t know what the current post is, and fails. This is what you’re seeing in functions.php. When functions.php is loaded, WordPress hasn’t set up the post loop, or queried the database, it’s still in the process of loading the theme and plugin files. The earliest event/hook that the $post is set, would be the wp event, your code runs earlier than this.

So instead, lets refer to the core load diagram, which says it’s safe to run code from the init hook and onwards. I’m going to suggest using the next hook, wp_loaded instead, but change this at your discretion:

function karmacoma_206593() {
    $value = get_field( "text_field" );
    if( $value ) {
        echo $value;
    } else {
        echo 'empty';
    }
}
add_action( 'wp_loaded', 'karmacoma_206593' );

Here I’ve put your code inside a function and told WordPress to call it on the init event/hook/action. To make sure it doesn’t clash with any other code you have, I’ve used your username and the ID of this question as the functions name.

Next, we have 2 new issues you’re unaware of. First, your if statements check could be better. For example, if your value is false, your check will fail, even if it’s a valid value, so I’m going to improve it by using empty:

if( !empty( $value ) ) {

Secondly, you’re outputting the value of this field without any form of escaping. What if the value of the field is a script tag? Lets secure this code by using esc_html to strip out any html tags:

echo esc_html( $value );

Giving us this:

function karmacoma_206593() {
    $value = get_field( "text_field" );
    if ( !empty( $value ) ) {
        echo esc_html( $value );
    } else {
        echo 'empty';
    }
}
add_action( 'wp_loaded', 'karmacoma_206593' );

Leave a Comment