WordPress Development for Beginners: Learning PHP

Becoming a WordPress developer goes hand-in-hand with learning PHP, the popular server-side scripting language WordPress is built on.

Originally created in 1994, PHP is a powerful and free open source tool for creating dynamic and interactive websites.

We’ve added a bunch of new courses to the Academy! Why not give it a try – absolutely FREE!FIND OUT MORE

This is the second post in our five-part series for beginners, teaching you the fundamental concepts of WordPress development so you can take the leap from tinkerer to developer. By the end of the series, you will be able to create your own rudimentary themes and plugins, and flesh them out with your own features.

In this tutorial, you’ll learn the basic syntax of PHP, the logic behind how it works, and I’ll walk you through coding examples.

Note: For this series, it’s important that you already have a thorough understanding of HTML and CSS as both of these languages are essential building blocks when working with WordPress.

Let’s get started.

Missed a tutorial in our WordPress Development for Beginners series? You can catch up on all five posts here:

What is PHP?

PHP is a server-side scripting language. To understand what that means, let’s compare it to HTML.

When you visit a simple HTML page, your browser makes a request to the server that contains it. The server figures out which file you need and sends it to you as-is. Your browser interprets the HTML code and displays it.

In comparison, when you visit a PHP page there is an additional step. Your browser sends a request and the server finds the file(s) you need. Before sending anything back, the server processes the PHP files, resulting in a final HTML output. This is sent back to your browser, which displays it as usual.

This is why you can look at any website’s source code and never see any PHP code, only HTML, even if the site is written in PHP.

So why would the server need to do the processing? What’s the point of all this? It allows us to create dynamic websites and code much more efficiently.

Let me give you two simple examples.

In HTML everything is static. You could create a page that displays “Good morning” or “Good evening,” but you couldn’t just show one or the other, depending on the actual time. In PHP you can because the server can process your code and take the actual time of day into account. Here’s what the logic for it would look like:

This isn’t real code of course, but it follows the logic of PHP. The server determines which statement is true and will display only one of the headings.

Another great example is Twitter or any other site that serves user-made content. If Twitter only used HTML, someone would have to quickly regenerate your Twitter feed each time you post – not exactly an efficient use of time. To put it into perspective, there are almost 1 billion Twitter accounts, so the company would need 1 billion HTML files, one for each user, in a folder somewhere.

With PHP, the problem of regenerating feeds could be solved with just a handful of files (though is possible to do it with a single file) quite ingeniously. We’ll come back to this example later in this tutorial.

Getting Started

Before we begin, I want to note that in the early stages of studying PHP you might not get what it has to do with websites. This is a completely normal reaction and it’s exactly what I thought when I originally started learning PHP. The first steps are a bit abstract, but by the end of this article you’ll see the light.

In order to test and practice what you’ll be learning in this tutorial, you will need an Apache server. This can be a test site online but it can also be a local server.

I recommend creating a local test server. Here’s how to do it:

First, download and install Virtualbox and Vagrant. Create a directory anywhere on your computer to store your project files. I have a “websites” folder in my user directory, in which I’ve created a “phptutorial” directory. I’ll refer to this as the “main project directory” throughout the rest of this tutorial.

Once you created the directory, open the terminal on Linux or OSX, or the command prompt on Windows, and navigate to the folder. If you have created the same folder structure as I have, you can type cd ~/websites/phptutorial on Linux or OSX. On Windows, you can type cd %HOMEPATH%/websites/phptutorial. Once in the correct directory, paste the following command:

This will take quite some time to complete as it will download and install a 700MB operating system. You only need to wait it out once, so get some cocoa while it finishes.

Once completed, you will be able to access your site at http://192.168.33.21. If you restart your computer, you’ll also need to restart your server, which you can do by navigating to the main project folder in the terminal and typing vagrant up.

The main project file is now your root folder. Create an index.html file in there with any content and it should be rendered correctly when you visit your website at http://192.168.33.21.

First Steps

First up, let’s look at PHP tags, variables, values, and echoing.

Create an index.php file in your main project folder and type “Hello HTML” in it. To verify it is working, visit http://192.168.33.21, and you should see the string displayed.

A very important rule is that only content within PHP tags is considered PHP code, anything else is considered HTML. This is why our Hello HTML text shows up. PHP tags begin with <?php and end with ?>. Anything in-between those tags is considered PHP.

The code above shows how PHP tags are used and also shows echoing. When you echo a value you are telling PHP to display it. The result of the code above will be “Hello HTML Hello PHP”. The first part is considered HTML because it is not within PHP tags while the second part is echoed by PHP code. Note that you must enclose your text within quotes.

Variables allow you to store values without displaying them. Variables are used extensively to hold many different things. Let’s look at a basic example:

Here, I’ve stored the value “Daniel” in a variable called $name. Instead of echoing “Daniel” directly, I am echoing whatever the value of $name is. This seems a little redundant here but if the variable is used in a lot of places we can change everything by changing the value of the variable in one place, instead of having to overwrite it everywhere.

Note that two lines of code must be separated with a semicolon. If your code produces an error, chances are you have forgotten to put a semicolon somewhere – a common mistake and frustration for coders everywhere!

Values can be of numerous types. So far we’ve only looked at one: the string. A string is a sequence of characters and must be enclosed within quotes. Another frequent one is an integer. An integer is any whole number and it should not be placed within quotes.

One of the most important value types is arrays. Arrays hold multiple values, which can all be different types.

As you can see, arrays are created using the form array( value1, value2, value3 ). The values should always be written as they are defined when working outside an array. Strings should be quoted, integers should not be quoted, and so on.

I don’t want to get too much into arrays here, so before continuing please take a look at this fantastic tutorial on arrays at W3Schools. The most important parts of this tutorial you should read about are on how arrays can be created, how values can be added, and what an associative array is.

A Simple Example

So what can all this be used for? Right now, what we’ve looked at so far isn’t enough to whip up a website but a practical example is definitely in order.

Let’s look at the bare bones of a simple weather forecast application:

There are a few things that are new, but I think the example speaks pretty clearly. Let’s go through it line-by-line.

Initially, we create two variables: once is a string holding the value “C” for Celsius, and the next variable is an integer, 29, which is intended to hold the actual temperature.

The goals here are simple: display some text that tells us the current temperature using the value from our temperature variable in the chosen unit of measurement, celsius or Fahrenheit.

The next line is an if statement, which is performed only if the value within the parenthesis is true. The condition is: $unit == 'F' which translates to “if the unit value is ‘F'”. Currently, it is not, so let’s skip the whole if block.

On to the last line.

The forecast is hard-coded to start with “The weather today will be great, a Sunny “. Depending on the value of our $temp and $unit variables, the ending will be different. The dots between strings and variables concatenate them or join them together.

So we simply substitute our values: $temp should be 29 and $unit should be “C.” So the final output is:

The weather today will be great, a Sunny 29C

Now, what happens if we change the $unit to “F”? First of all, the if statement kicks in because it becomes true. This means that everything between the curly braces gets executed as well. In the example, I assigned a new value to the $temp variable.

I took the original value, multiplied it by 9, divided it by 5 and added 32 – this is the math for converting celsius to Fahrenheit. The new value for $temp should be 84.2, and the new value for $unit should be “F.” Substituting the variables with their values in the final sentence results in:

The weather today will be great, a Sunny 84.2F

This example is still a bit useless to us, but it starts to show the power of PHP. Note how we arrived at the final output by basically replacing variables with values. It helps to get into the mindset of “replacing placeholders” because it is essentially what PHP is about.

In a real world example, we would retrieve the current sky conditions and instead of hard-coding “great, a Sunny”, we would use the actual conditions. We might also want to forecast for tomorrow or the day after, which would result in “today” being replaced by a placeholder as well.

In addition, the current temperature would obviously not be hard-coded into the code, it would need to be retrieved from somewhere. Even though this adds a couple of layers of complexity, the essence remains the same – we’re grabbing data from somewhere and placing it in our output.

If Statements and Loops

We’ve already seen an if statement in action. An if statement evaluates the condition in the parenthesis and selectively processes code based on the result. If the result is true the code is processed within the curly braces otherwise it isn’t.

If statements can also have related else if and else statements. else if statements are always written after if statements. If the original if statement turns out to be false, the else if statement is then checked, using the same rules as before. You can have any number of else if statements.

Finally, the else statement is evaluated if everything has been false leading up to it. You don’t have to have an else if statement within a group, you could only have an if and an else statement together.

Take a look at the following examples for syntax and clarification:

One more thing to note here are the rows beginning with double slashes. A double slash allows you to add a single-line comment anywhere in your code. You can add multi-line comments by starting with /*, writing whatever you’d like and ending it with */.

Loops come in a number of shapes and sizes, four to be exact. They all allow you to run the same code a number of times in succession. You may hate them now, but they will become your closest ally when you become more proficient at coding!

Let’s start with a foreach loop. A foreach loops goes through all members of an array and executes the given code. Here’s a quick example that outputs an HTML list:

The key here is understanding the content of the parenthesis, which is $names as $name. The first part is the name of the array you want to loop through. The second is the name of the variable you can refer to in order to get the value of the array member you are currently at during the loop.

In our example, the loop will be performed three times. On pass number one, the value of $name will be “Daniel Pataki,” on the second pass it will be “Raelene Morey,” and on the last pass it will be “James Farmer.”

If you followed my advice earlier in this tutorial and read up on arrays, you will know what an associative array is. The following example displays my details in a list, from an associative array:

The parenthesis now contains three variables: $details as $label => $value. We are going through the $details array. On each pass we’ll call the key $label and the value $value. On the second pass, the $label will be “Age,” the $value will be 30. The code results in something like this:

  • Name: Daniel Pataki
  • Age: 30
  • Twitter: http://twitter.com/danielpataki

If you want to learn more, take a look at other types of loops available: while loops, for loops, and do-while loops. They are all very similar, but with minor differences.

How WordPress Post Lists Work

Let’s now take a look at an example more relevant to using WordPress: how a post list works.

The code below does not mimic WordPress exactly, but the gist is there. Imagine posts as being parts of a big associative array. Your home page’s code simply loops through this array and places the appropriate data in the appropriate place in some HTML code:

Functions

In a way, functions serve the same purpose as variables – a way to substitute code. Functions can take a block of code and store it for later (and multiple) use.

Let’s look at a very simple example using our post loop above. The part where we echo the post elements will probably be used in a number of pages on a website – the homepage, category archive pages, author pages and so on. We would use the same block of code again and again. This is exactly when functions come in handy.

The code above is not shorter, but any time we want to display a post in the future we can just type display_post( $post ); making it a lot more efficient in the future.

So how does this all work?

Let’s approach this by looking at the function at the top of the code first. I’ve named the function display_post() and in the parenthesis you can see that it expects one parameter. We know that this parameter should contain post data so it would be an associative array containing the data of a single post. I’ve named it $postdata.

Within the curly braces we include all the code we want to execute when the function is called. This is the same code as we had before, I just needed to rename all variables to $postdata, the name of our parameter, which we can use anywhere within the function.

At the bottom of the code, you can see that displaying a post is now much cleaner, we just used display_post( $post ). Now, I bet you’re confused about the naming. Why is it $post in one place and $postdata in the other?

Let’s go through the code.

Functions are only run when they are called, so the first thing that actually matters in our code is the definition of the $posts array. We then create a loop, just like we did before. Within the loop, the variable that contains the data for a single post is $post, so far nothing has changed from our function-less example.

Now, instead of having the mass of code in there, we simply defer to a function. We call the display_post() function. We know that we need to pass it some data – the data of a single post. Which variable contains that information right now? The $post variable, this comes from the definition of the loop.

Next, scroll up to the function. It will now be executed. In the function, the first parameter is named $postdata. This simply means that within the function, we will refer to the data passed to the first parameter as $postdata.

Creating an Excerpt

Functions can have multiple parameters and default parameter values. Let’s create a function that can make any text into an excerpt by cutting it down into pieces. We want our function to be as flexible as possible, able to control the excerpt length, and a string to append to the end.

We’ll make the first parameter the text we want to shorten, the second parameter control the length, the third the appended text.

Let’s start by giving our function a frame to work within:

Note that I’ve given default values to the parameters. This means you can invoke the function without passing the second and third parameters. If you do this the function will presume you want to create a 200 character long excerpt and append three dots afterward. Let’s flesh out this function:

I’ve added plenty of new things in there, so let’s go through each new addition in detail.

It all starts with an if statement, which checks if the text given is actually longer than given length. It does this using a function built into PHP called strlen(). This function takes a string as its parameter and returns its length. If the $text length is less than $length the text is simply returned – we’ll talk about what returning means in a moment.

Otherwise, we create an excerpt using the substr() function. This function cuts up a string and requires three parameters: the text to take a chunk out of, the starting position of the chunk, and the length of the chunk. We want to start at the beginning of the text and cut off $length characters, which is why I’ve added 0 and $length.

Finally, we add the append string to the end. I’ve used the .= notation to do so. This is the same as writing $excerpt = $excerpt . $append. In the last line, I returned the $excerpt variable.

So what is returning? So far we’ve mostly been echoing things, but in many cases we don’t want to display the result of our “calculations.” The strlen() function is a good example. You don’t actually want to display the length of the $text variable, you just want to use it in the code to achieve something. strlen() returns its value, allowing you to use it elsewhere.

When you return a value with a function you would either use it right away (like in strlen()‘s case), or assign it to a variable: $short_text = get_excerpt( $content ). You could then echo $short_text later when needed.

If you want to learn more about functions (you should!), check out W3Schools’ tutorial on functions .

Further Reading and Study

PHP is the basis for all themes and plugins so you’ll need to rely pretty heavily on this language. When working in a WordPress environment, you’ll use PHP functions (like strlen and substr), but there are also hundreds of functions created especially for WordPress by the core development team to help you. We’ve explored some of these functions in upcoming tutorials in this series.

In this lesson, we’ve covered the basics you need to know to get started with WordPress development, but the truth is we’ve only just scratched the surface! It’s important that you read up on and explore each of the topics covered in this tutorial in more depth and practice, practice, practice!

Check back here next week for part three in our series, WordPress Development for Beginners: Building Themes.

You can also read the first post in this series, WordPress Development for Beginners: Getting Started.

But in the meantime, check out the following resources to expand and cement your PHP knowledge:

  • PHP The Right Way – A comprehensive and well-structured introduction to PHP if you’re new to the language.
  • W3Schools – W3Schools is a free web developers site, with tutorials and references on web development languages such as HTML, CSS, JavaScript, PHP, SQL, and jQuery, covering most aspects of web programming.
  • Tizag – Tizag.com was created as a free stepping stone to the budding webmaster and a handy reference to the veteran developer. The site offers a tutorial that teaches the basics of PHP.
  • Treehouse – A premium site for learning to code that features over 1000 videos created by expert teachers on web design, coding, business, and more.
  • Codecademy – A free site for learning to interactively that features a great course on getting started with PHP.

Did you find this tutorial helpful? Why do you want to learn WordPress development? What do you want to know more about? Let us know in the comments below.

We’ve added a bunch of new courses to the Academy! Why not give it a try – absolutely FREE!FIND OUT MORE