Learning PHP for WordPress Development: Introduction to PHP Functions

php functions for wordpress development

This article is an accessible dive into one of the bedrock concepts of modern programming: functions.

In this section of our guide to PHP for WordPress developers, we take an accessible dive into one of the absolute bedrock concepts of PHP, or any modern programming language: functions..

David’s guide to the very basics of PHP—what a variable is, how the <?php and ?> tags work, and a few other essentials—can be helpful if any of the material below confuses you.

The general workings of PHP functions are not too hard to understand, so take fifteen minutes and see where this article gets you. You might feel a lot more code-savvy by the end.

What PHP Functions Are

PHP functions are defined, repeatable bits of work.

In programming languages, including PHP, functions are defined, repeatable bits of work. David calls them “stored procedures,” which is a good name for this basic notion of “repeatable bits of work.”

If the human body was run by a programming language, its functions would include things like eat(), look(), walk(), and sleep(). The idea of “bodily functions” means “functions” in the same fundamental way as programmers mean it.

PHP, whether inside or outside WordPress, has a big list of hundreds of functions that you can always run anytime you’re writing in PHP. They’re simple things like print_r() or date(), as well as weirder ones like explode() or ob_start(). Unlike the human body’s functions, these are actually written in a programming language—PHP itself—so you can Google any of them and see what they do.

A WordPress website has its own functions: things like update_post_meta(), add_user(), and get_the_title(). These are also written in PHP, and you can Google them to see what they do.

In all three cases, functions refer to defined bits of work that, because we’ll be needing to do them often, we write down—define—centrally in one single place, and then invoke—call—whenever needed.

What All PHP Functions Have in Common: function and ()

PHP is full of all kinds of stuff, not just functions. How can you look at PHP code and know when you are, and aren’t, working with a function?

In my opinion, the most comforting rules are ones that have no exceptions. Here are two awesome rules in PHP that have no exceptions, and which you can use to know whether you’re working with a PHP function or not:

1. The Word function

All PHP functions have the word function on the line where they’re originally defined. If it doesn’t have the word function, it’s not a function definition, although it may be somebody calling a function that’s previously been defined.

Let’s see this in code:

<?php

// This is definitely a function definition, since it's got the word "function"
function say_hello() {
	echo 'Hello world!';
}

// This is definitely not a function definition, since it doesn't have the word "function"
$var = 100;

// This is definitely not a function definition (it does happen to be a function call, though)
say_hello();

?>

To get the most out of this rule, read below to understand the difference between defining a PHP function and calling it.

You can even use this knowledge to search for where a function is defined. If you see the line <?php say_hello(); ?> and wonder what the say_hello() function does, you can look for where it’s defined by searching the code for function say_hello, and you’ll always find something.

2. The () Bit

All PHP functions, when being either defined or called, will contain the characters ( and ) in that order. A few examples of this:

<?php

// Defining the say_hello() function
function say_hello() {
	echo 'Hello world!';
}

// Calling the say_hello() function
say_hello(); // Will output "Hello world!"

// Defining the say_something() function with arguments
function say_something( $phrase = 'Hello world!' ) {
	echo $phrase;
}

// Calling the say_something() function with passed-in arguments
say_something( 'Hello PHP lovers!' ); // Will output "Hello PHP lovers!" 

?>

Whether you’re defining or calling a function, with arguments or not, it’s always got the ( and ) characters in there. If there’s no (), you’re not working with a function.

This is also why function names are commonly written with the () directly in the title: not get_post_meta, but get_post_meta().

So that’s a bit of an initial guide to help you know when you are and aren’t looking at a function in PHP. Now let’s get into how functions actually work.

PHP Functions are First Defined, then Called

PHP functions obey a clear “call-and-response” pattern: they are first defined, and later called.

As in most programming languages, PHP functions obey a clear “call-and-response” pattern: functions are first defined, and later on those functions are called.

To define a function means to describe what that function does. Defining a function doesn’t do anything yet: it simply says what the function will do once it’s called.

Let’s see defining a function in code:

<?php

// First we're going to *define* the say_hello() function
function say_hello() {
	echo 'Hello'; // This is what the function *will do* once it's called
}

Once you’ve defined a function, you can then call it whenever you want. To call a function is to invoke it: it means to actually bring about the functionality that you previously specified when you originally defined the function.

You can’t call a function that hasn’t yet been defined, in the same way you can’t eat a meal that hasn’t yet been cooked. In PHP, you’ll get a fatal error if you try.

Let’s see all of that together:

<?php

// First we're going to *define* the say_hello() function
function say_hello() {
	echo 'Hello world!'; // This is what the function will do when called
}

// Now we're going to *call* the say_hello() function
say_hello(); // This will print "Hello world!" into the HTML document

// Uh oh! We're calling a function that isn't defined. We'll get a fatal error if we do this.
say_something_else(); 

?>

As a final note, some fancy kids will write something called “anonymous functions” that are defined at the same time they’re called. They’re unusual, and there’s never a real need to write one, so don’t worry about them other than to have heard the term.

PHP Functions Can Accept Arguments

A function’s arguments are variables: things that can change from one time the function is called to the next.

The next big chunk for learning PHP functions is to get your head around function arguments. This concept can be initially confusing, but it’s also where a lot of the power of PHP functions is stored.

A function’s arguments are variables: they are things that can change from one time the function is called to the next. These changes will affect the output of the function, while leaving the function itself basically the same as a coherent “thing that someone does.”

To give an analogy from real life, our bodies have an “eat function”: eat(). But that function that can accept a wide variety of specific things that we might eat. We might eat an apple—eat( 'apple' )—one day, and eat an orange—eat( 'orange' )—the next day.

And of course the process of eating an apple and eating an orange is slightly different—because of the differences in the foods themselves—while remaining fundamentally the same process: eat().

It’s this basic idea of a single process that takes on differences that is at the core of function arguments. With that slightly philosophical example about eating, let’s now give you some real PHP code examples to, um, sink your teeth into.

A PHP Function with No Arguments

Some PHP functions simply have no arguments: there’s no variable we want to include that could make them behave differently at different times they’re called. Our earlier say_hello() function is an example:

<?php

// Defining the say_hello() function with no arguments
function say_hello() {
	echo 'Hello world!';
}

// Calling the say_hello() function (and passing no arguments)
say_hello(); // Always outputs 'Hello world!';

?>

A PHP Function with One Argument

Some PHP functions do pass in an argument—a value that will change at different times that the function is called. In the example below, the function say_something() has a single argument, $phrase. That argument is first mentioned inside the () bit next to the function’s name, and it’s referenced as a variable, $phrase, inside the function definition itself.

Then, when say_something() is called, different values for $phrase are passed in, again within the () bit of the function call. These passed-in values change the behavior of the say_something() function itself, leading to different output each time. Have a look:

<?php

// Defining the say_something() function with a single argument
function say_something( $phrase = 'Hello world!' ) {
	// This time what we'll be echoing is a variable!
	echo $phrase; // The value that $phrase takes is controlled by our single passed-in argument.
}

// Calling the say_something() function without passing in an argument
say_something(); // This will output the default value of $phrase, which is "Hello world!"

// Calling the say_something() function with a passed-in argument
say_something( 'Hello PHP lovers!' ); // This will output "Hello PHP lovers!"

say_something( 'Totally other statement!' ); // This will output "Totally other statement!"

?>

There’s a lot to take in here. Whether or not everything above makes sense to you, check that you understand the basic intuition of what a function argument is, and does:

  1. Rather than always being the same thing, the text our function outputs is now a variable, $phrase. This is the function’s single argument.
  2. The code that defines the function refers to that $phrase variable, without the function knowing what its specific value will be when called.
  3. When we call or invoke the function, we pass in a specific values for the function’s argument. These different passed-in values change what the function ultimately outputs—even though the function itself does not change.

A PHP Function with Multiple Arguments

Many PHP functions have multiple arguments. These arguments can be of mixed data types. In the example below, there are two arguments, one expecting a string and the other expecting a number.

<?php

// Defining the say_something() function with a single argument
function say_something_and_maybe_repeat_it( $phrase = 'Hello world!', $repetitions = 1 ) {
	$i = 0;
	while( $i < $repetitions ) :
		echo $phrase; // This time we're echoing a passed-in argument: in other words, a variable!
		$i++;
	endwhile;
}

// Calling the say_something() function without passing in arguments
say_something_and_maybe_repeat_it(); // This will output "Hello world!" once

say_something_and_maybe_repeat_it('Hello?'); // This will output "Hello?" once

say_something_and_maybe_repeat_it('Hello there?', 2); // This will output "Hello there?" twice, like: "Hello there?Hello there?"

?>

Again, there’s a lot to take in here—including your first incrementer (the $i counter) and while() loop—so don’t fixate on understanding the above code completely. But do check that you have a sense for the basic points that:

  1. We’ve created two variables this time around: what to say, and how many times to say it.
  2. We define those two variables as arguments, when we define the function.
  3. We pass in specific values for those arguments, each time we call the function.

Patterns in PHP Function with Arguments

In all the examples above, notice that a function’s arguments (if it has any) go inside the () bit that all functions have. That’s why all functions have that bit: because arguments and functions themselves are so closely related.

What Good are PHP Functions?

Functions are one of the absolutely most central concepts in PHP, or for that matter just about any programming language. They’re as central to programming as our muscles are to our bodies.

So what, concretely, can PHP functions do for our work as PHP developers? At least two enormous things:

1. We Can Write Our Own Functions to Do Useful Stuff

An example that often comes up in my mind is the need to auto-update the year in your site’s footer. We’ve written a Quick Guide that walks you through doing this:

How to Auto Update the Copyright Year in a WordPress Footer

Now that you know how to call PHP functions, it’s a lot easier for me to tell you that PHP has a default function—in other words, it’s already defined in PHP by default—called date(), and that when we call date() with certain kinds of arguments, what we get is today’s date formatted in terms of things like years, months, days, minutes, and seconds.

So when I tell you that <?php echo date( 'Y' ); ?> is the way to output the current year into your site’s footer, you already know how to call functions with arguments, and that code snippet makes a lot more sense.

2. We Can Use WordPress’s Very Huge and Very Powerful PHP Function Library

One of the main reasons to use WordPress itself is for its vast library of WordPress-only PHP functions. These functions have all been defined (see above) within WordPress’s core software, and we can call them (that is, use them) in our own PHP code anytime we’re working within WordPress.

Here are a few example functions from WordPress’s PHP function library:

WordPress’s custom PHP functions make up the giant “instrument console” that lets you do stuff with WordPress.

These PHP functions, and literally hundreds of others, are the foundation for how a PHP developer works with WordPress. They are the giant “instrument console” that lets you actually do stuff with WordPress, and what they have in common is that they’re all custom functions, written in PHP, that are part of WordPress’s core code itself.

wordpress php function library

Instrument panel, function library: similar idea

And Now You’re Functionally Awesome

Thanks for reading this guide to PHP functions. You’re on your way to understanding the PHP you need to know for WordPress development. Let us know if you have any questions or thoughts, either in the comments below or in our Facebook group.


4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Karina Stavenes
March 9, 2019 5:05 am

That was a fantastic tutorial and one of the best I’ve seen, with everything so well defined. Thank you so much! After reading the other ones by David Hayes, and now reading this one, it all made perfect sense. Yay!

dimiter kirov
February 18, 2019 5:46 am

That’s an awesome tutorial!

Israel Barragan
February 15, 2019 10:24 pm

This is a very clear and complete guide for new PHP Developers. Great Job !

Ikpe okafor
February 15, 2019 4:00 pm

Very Nicely laid out.