Search code examples
phpcsswordpresswordpress-themingadvanced-custom-fields

How to avoid `Call to undefined function` fatal error in a custom PHP file for WordPress


We're in WordPress. We're trying to make a customizable CSS style sheet. Using Advanced Custom Fields plugin, we've created a custom field called color. We'll use it as an option to define a color value, in HEX format, as used in CSS.

We've created a PHP file just to be used as CSS style sheet. It's loaded from our WordPress as a CSS resource. This PHP produces a CSS code where we want to use our color option as color property for some elements.

But, here is the problem, that PHP generates this error:

Fatal error: Uncaught Error: Call to undefined function the_field()...

This is the PHP code:

<?php
header('Content-type: text/css');
the_field('primary_theme_color', 'option');
$color = the_field('primary_theme_color', 'option');
?>
:root {
    --primary-color:<?php echo $color; ?>;
}
* {
    background-color: var(--primary-color);
}

We know that the_field() function exists inside Advanced Custom Fields plugin, so why it doesn't work?


Solution

  • Error info can't be clearer: you are pretending to use a function that is not defined. This function is the_field(), and yes, this is a known function from Advanced Custom Fields plugin for WordPress, but this is what it happens:

    You have made a PHP script to generate a CSS style sheet. Inside this script, you need to use the_field() function. This script runs as standalone, so, when you try to use that function, it doesn't declared. You need to load WordPress before.

    Just add this line before invoke the_field() function:

    require_once 'pathToYourWordPressRootDir/wp-blog-header.php';
    

    Of course, you need to replace pathToYourWordPressRootDir with correct value. For example, if your PHP file is inside wp-content/themes/yourTheme/assets/common/, then it will be:

    require_once '../../../../../../wp-blog-header.php';
    

    Or, more reliable:

    require_once dirname(__FILE__) . '/../../../../../../wp-blog-header.php';
    

    Note.- In many posts, you can find that the way to load WordPress is requiring wp-load.php instead of wp-blog-header.php. But I guess wp-load.php is heavier, so I prefer wp-blog-header.php, and I tried yet using it and it works fine!

    Remember.- Advanced Custom Fields plugin must be installed and active.

    Important

    The function the_field() doesn't return anything, just does an echo of get_field(). So, to get the value you want, you need to use get_field() function:

    $color = get_field('primary_theme_color', 'option');