How to fix the Error Uncaught Error: Call to undefined function trailingslashit()

Did you try to update PHP to version 7.4, or 8.0. or 8.1 and your website goes down with an http error 500 and the error message “Uncaught Error: Call to undefined function trailingslashit()“?

The “Call to undefined function trailingslashit()” error is typically encountered in WordPress projects. This error occurs when the code tries to call the trailingslashit() function, but PHP can’t find it. This function is usually defined in the WordPress core file wp-includes/formatting.php.

To fix the undefined trailingslashit error, follow these steps:

  1. Check if wp-includes/formatting.php is present and not corrupted:

Make sure that the formatting.php file exists in the wp-includes directory of your WordPress installation. If the file is missing or corrupted, you may need to re-upload it from a fresh copy of WordPress. You can download the latest version of WordPress from https://wordpress.org/download/.

  1. Ensure the wp-load.php file is included correctly:

In your custom plugin or theme, make sure that you’ve included the wp-load.php file before calling the trailingslashit() function. This file is responsible for loading the WordPress environment and core functions. You can include it using the following code snippet:

PHP
require_once(ABSPATH . 'wp-load.php');

If you don’t know the path to wp-load.php, you can use the following code snippet to locate it:

PHP
$wp_load = dirname(__FILE__) . '/wp-load.php';
while (!file_exists($wp_load)) {
    $wp_load = dirname(dirname($wp_load)) . '/wp-load.php';
    if (dirname(dirname($wp_load)) === '/') {
        break;
    }
}
require_once($wp_load);
  1. Check for conflicting function names:

It’s possible that another plugin or theme has defined a function with the same name trailingslashit. If this is the case, you can disable the conflicting plugin or switch to a different theme to resolve the issue.

  1. Manual function declaration:

As a last resort, you can manually define the trailingslashit() function in your plugin or theme. However, this should be avoided if possible, as it may lead to conflicts and compatibility issues in the future. If you must define it manually, here’s the function definition:

PHP
if (!function_exists('trailingslashit')) {
    function trailingslashit($string) {
        return rtrim($string, '/') . '/';
    }
}

Remember, always backup your files and database before making any changes to your WordPress installation. That could be a good time to the changes first on a staging site or create a full site backup with WP Staging first.