WordPress at Your Fingertips

The functions.php theme file in WordPress

Everyone familiar with WordPress has heard of the functions.php theme (template) file. However, not everyone understands its purpose, seeing in it only a file that stores various php functions. On the Internet, as I have on this site, it is often suggested to add PHP code in this file. However, not every such a code will work. Not because it broken, but because it doesn't fit the logic of use.

Also, when editing functions.php newcomers make mistakes that cause the site to stop working.

In this article, I will try to consider all these points: when it is necessary to use functions.php and when it is better not to do, what errors might occur while editing functions.php.

functions.php Features

functions.php is located in the theme folder and is loaded every time, while viewing the front part of the site, in the admin panel and even during AJAX requests. There is no case where functions.php will not be included and it opens up a lot of opportunities for developers.

For example, the following code, inserted in the theme's functions.php file will expand the theme's capabilities - to include support for post thumbnails:

add_action( 'after_setup_theme', 'wp_kama_theme_setup' );
function wp_kama_theme_setup(){
	// Thumbnail support
	add_theme_support( 'post-thumbnails' );
}

Another example, the code will replace the text in the footer admin panel of WordPress, with data on the number of requests to the database, the time of generation of the page and memory usage:

## Data about the number of database queries in the footer of the admin panel
add_filter( 'admin_footer_text', 'wp_usage' ); // in the admin panel
add_filter( 'wp_footer', 'wp_usage' );         // on site
function wp_usage(){
	echo sprintf(
		__( 'SQL: %d in %s sec. %s MB', 'km' ),
		get_num_queries(),
		timer_stop( 0, 3 ),
		round( memory_get_peak_usage()/1024/1024, 2 )
	);
}

functions.php vs plugins

  • "Plugins are slower than the code in the functions.php file", say the uninformed - this is not true!

There is no difference in the speed of the code, no matter whether it is plugged in through a plugin or through the functions.php file. Read more in a separate post.

Theoretically, inserting code into functions.php is the same as installing a plugin, but it's not the same thing. After all, if you change the theme, we get a completely different functions.php and all changes will be lost, but the plugin will remain until you change the theme. With this in mind you should use the functions.php file. If you are adding functionality not only to the theme, but to the site as a whole, then it is worth thinking about add it in the form of a plugin.

The second example above, "Data on the number of requests to the database in the footer of the admin". Logically not suitable for use in the file functions.php. Because if we change the theme, we will lose this functionality, and it is used in the admin panel and is needed regardless of what theme is used.

So, let's remove it from functions.php and make a plugin out of it - it's easy!

To create a plugin you need to create a file with the code below (file name can be any), add it to the plugins directory /wp-content/plugins/ and activate the plugin in the admin panel:

<?php
/**
 * Plugin Name: Any plugin name here
 */

// plugin code

add_filter( 'admin_footer_text', 'wp_usage' );
function wp_usage(){
	echo sprintf(
		__( 'SQL: %d in %s sec. %s MB', 'km' ),
		get_num_queries(),
		timer_stop( 0, 3 ),
		round( memory_get_peak_usage()/1024/1024, 2 )
	);
}

If you do not want to see yet another plugin in the admin panel, you can use Must-Use plugins.

What functions.php is really for

As I wrote above: functions.php is needed to extend the functionality of the theme and only for that! In this file you need to add all sorts of code that is needed for the theme directly, but not for the site as a whole.

If any resource (site) you are asked to add code to the functions.php file, and the function code does not relate directly to the theme, then do not be lazy to make a plugin from this code and perhaps in the future avoid the unexpected loss of functionality added earlier.

How functions.php loads

functions.php is plugged during the initialization of the current theme, after all WordPress features and all active plugins are plugged. I'll briefly describe the timeline for WordPress loading, which shows when important files are plugged in:

index.php
	wp-blog-header.php
		wp-load.php
			wp-config.php
				wp-settings.php
					// The most basic functions are connected (connection to the $wpdb database and the hooks system)
					// basic filters are connected.

					// SHORTINIT: Stops loading where there is only the most basic:
					// if ( SHORTINIT ) return false;

					// connects the entire WordPress environment:
					// basic functions, filters

					// must-use plugins are plugged in, then following action
					// is triggered:
					do_action( 'muplugins_loaded' );

					// plug-ins are connected, then following event is triggered:
					do_action( 'plugins_loaded' );

					// global variables are set:
					// $wp_the_query, $wp_query, $wp_rewrite,
					// $wp, $wp_widget_factory, $wp_roles ...

					do_action( 'setup_theme' );
					// the current theme is set
					// theme file >>>>>>>>>>>> functions.php <<<<<<<<<<<< included
					do_action( 'after_setup_theme' );

					// event when the WP environment, all plugins and the theme are fully connected,
					// but nothing has yet to be displayed:
					do_action( 'init' );

					// Checking the status of the site for multisite

					// the same as `init` but after the status check
					// (PHP might not work up to this line)
					do_action( 'wp_loaded' );

		wp() // fills in the main WP query and all global variables associated with it

		wp-includes/template-loader.php // connects the template file

The process of WordPress loading, and functions.php in particular, is is fully described here. Here is a illustration:

WordPress Download Scheme

Errors in functions.php when inserting code

Repeatedly encountered questions about errors, such as: "After installing the code in the functions.php file site stopped working - white screen. What to do?". I myself have faced with similar once.

For me, some solutions to this problem for a long time, remained a mystery - like nothing I did, and even the dance with bamboozle was not, but once and it all worked. Why does this happen? Let's look at possible situations due to which the site may "break" and their explanation:

  1. You insert ready-made code - the site stops working.
  2. You edit functions.php - the site stops working.

Most often, the problem is in the opening and closing PHP tags <?php and ?>. Usually, if the inserted code has at the beginning and end of these tags, they must be removed. Also, the functions.php file must not display any text (HTML code or other content). Text output is only allowed inside functions that will later be used in the template files or that are attached to hooks (see below for details).

No characters are allowed before <?php or after ?>, including invisible characters (line break), because functions.php is plugged before http headers (such headers contain different data, e.g. that this is an html document; that site has utf-8 encoding; etc.). According to the rules of PHP, the content should be displayed after the headers are sent. And anything beyond <?php and ?> is content - text that is displayed, even the invisible \n character. That's why such text causes white screen error.

There are four things to keep in mind:

#1 Correct nesting

Example, we had this structure:

<?php
........here is the code.........
?>

If you added php code in this way, it will cause an error or, worse, a white screen when the error display is disabled:

<?php
........here is the code.........
   <?php
   ...... here is your inserted code ........
   ?>
........here is the code.........
?>

The right code should be like this:

<?php
........here is the code.........

   ........ here is your inserted code ........

........here is the code.........
?>

#2 No line breaks, no spaces, no text before <?php and after ?>

Such code will cause an error:

<?php
 ...... here is the code ........
?>
<?php
 ...... here is your inserted code ........
?>

But this will not:

<?php
 ...... here is the code ........
?><?php
 ...... here is your inserted code ........
?>

It makes more sense to write it like this:

<?php
 ...... here is the code ........

 ...... here is your inserted code ........
?>

It happens that the line break is put at the end of functions.php, that's when it becomes a real problem, because everything seems to be correct, but the site does not work. In fact, after ?> or before <?php there is an invisible line break symbol \n. This error looks extremely innocuous, something like this:

<?php
... start of file ...
  ...... here is the code ........
... end of file ...
?>
there's a blank line

For this reason, many developers remove the closing ?> tag altogether, this is acceptable in PHP. I recommend that you always do exactly that:

<?php
... start of file ...
  ...... here is the code ........
... end of file ...

#3 Using <?php and ?> inside a PHP function

If there is a function in functions.php, you can use the tags <?php and ?> inside that function, for example, to visually highlight the HTML code inside the function:

<?php
... start of file ...

function function_name(){
	?>
		 <div>html code</div>
	<?php
}

... end of file ...
?>

The point is that in this case the function only registers and does not perform any actions. Everything inside a function (between { }) does not work until that function is called, and such functions are usually called from a template file or through filters after HTTP headers have been sent. So in this example, we can ignore line breaks and use ?> and <?php as we please.

#4 Encoding

One more thing about the functions.php file: set the encoding to UTF-8 (UTF-8 without BOM). Otherwise, if the text in the file will be in Cyrillic, it will be displayed with incomprehensible characters.

1 comment
    Log In