Learning PHP for WordPress Development: A Comprehensive Guide
Mục Lục
Learning PHP for WordPress Development: A Comprehensive Guide
So you have a WordPress website and you’ve tweaked your theme, read a bit about template tags, and perhaps even modified your functions.php file in the built-in theme editor.
And now you want to take your skills to the next level and delve into more code.
Luckily, WordPress is a great place to start. There is a truckload of documentation available and the code is – for the most part – easily readable, self explanatory and not too difficult to remember.
In this article, I’ll give you a brief introduction to the world of WordPress programming. While this post is aimed at beginners, it does presume you’ve tinkered with WordPress before and you know basic HTML. I will assume that you know how to edit WordPress files and you’ve looked into a WordPress theme file – even if you didn’t understand what’s going on.
What we’ll cover in this guide:
Programming Languages Used in WordPress
WordPress uses a number of different programming languages. If one language has to be singled out as the “main” one it would be PHP. PHP is a server side language, which powers about 80 percent of the web.
WordPress also uses HTML, CSS and Javascript. HTML is used to give your website structure and is employed by all websites. CSS helps style your HTML structure. CSS makes your background white, your text dark-grey and positions the sidebar on the right. Javascript adds advanced features like sliders and other interactive features.
Finally, WordPress also uses MySQL, which is responsible for querying the database. MySQL is used to retrieve the last 10 posts, or all posts in a particular category from the database.
OK, so the bad news is that this is a considerable body of knowledge. The good news is that you don’t need to know everything to get started; in fact, you can get by with very little. I myself learned programming through WordPress about eight years ago by just copy-pasting examples from the documentation.
An Expert’s Advice
As I mentioned, I learned through tutorials, documentation, the work of others – I’ve been where you are now, and I went through all the phases you will. The difficulty with programming does not come from the complexity of the languages involved. When broken down into components, everything you learn is easy.
I find that programming is hard for two reasons. You need to know a lot of simple things and in order to create a successful product you need to be able to think in terms of systems, which takes a bit of practice.
What I wanted to make sure you know is that while learning to code for WordPress you will have plenty of #$#%!! moments. You will be frustrated with your lack of understanding early on, what you think is perfectly formed code won’t work, you’ll spend hours battling with it only to discover you’ve forgotten a semicolon. This is all perfectly normal. Every single successful programmer has felt this, it’s not just you. I promise that if you keep at it, you’ll be able to code a theme in no time.
No Such Thing as “WordPress Code”
It is important to realize that technically there is no such thing as “WordPress coding” and “WordPress code.” WordPress is a bunch of code written in PHP. Joomla and Drupal (two other content management systems) are also written in PHP.
Analogy to the rescue! Saying “WordPress code” is like saying “BMW Car.” A BMW, a Jaguar and a Nissan are all cars – they are all built with nuts, bolts and welding. The difference between them is how they are put together, the design philosophies and the assemblage practices.
WordPress, Joomla, Drupal and all the other systems and frameworks out there are all built with the same components. The difference between them is the coding philosophy and methodologies they employ.
How PHP Works
As I mentioned earlier, PHP is a server-side scripting language. In contrast, HTML is a client-side language. Let’s analyze HTML first to understand what this means.
The way your browser interprets HTML code is the following: When you visit an HTML page the HTML code is sent to your browser. Your browser processes the information and spits out something you recognize as a web page.
When your browser visits a page that employs PHP, an intermediate step is employed. First the PHP code is processed by the server. The result of this processing is an HTML page, which is then sent to your browser and displayed to you.
The additional processing by the server seems like an unnecessary step but far from it. Let’s look at a practical example with real PHP code:
Without any understanding of PHP code, we can already gather some information about it. Just by reading it you can discern that if a particular set of circumstances is true we display “Good night,” otherwise we display “good day.”
When you look at the source of the resulting web page there will be no trace of this code. All you will see is either “Good day” or “Good night.” This is because the server does the processing and only sends you the result.
In the example above I used the date function to determine what time it is. date( 'G' )
returns a number from 0 to 23 where 0 represents midnight and 23 represents 11pm. If the value of this function is more than 18 (it is later than 6pm) we display good night. Otherwise we display good day.
Now we know two things about PHP! It allows us to use if statements to display content based on our own criteria. We also know that it has functions, which help us out. The date()
function returns the current date in a given format. The strtolower()
function will turn any text to lower-case. A number of these functions empower you to do great things with PHP.
PHP in WordPress
With that last paragraph in mind, you can recognize PHP everywhere in WordPress. Let’s open the content.php
from the Twenty Fourteen default theme and take a look. This file is responsible for displaying the content of blog posts in the theme.
Let’s compare the first line of this file (discarding the comment on top)…
…with the output it generates when you visit the page:
We can deduce from the comparison that the the_ID()
function is replaced by the ID of the post in question. The post_class()
function adds a lot of classes to the HTML element. These help us in styling our posts later on. It’s not important at this stage to know why these specific classes are added, we’re just familiarizing ourselves with functions.
Further on, looking at lines 24 through 28 we can also see an if statement at work:
The if statement has is_single()
in it. This is a function which will be true if we are looking at a single post page, otherwise it will be false. If it is true and we are on a single page, we use the the_title()
function to output the title.
If it is false, we still use the the_title()
function, but we make sure it is a link to the single post page.
Notice that some functions are “empty” while some have bits and pieces within them. For example, is_single()
is an empty function while the_title()
has some gunk within the parenthesis.
The items within the parenthesis are called arguments. Each function has different arguments separated by commas, which you can learn about through documentation. The Codex article on the_title() shows us that this function has three arguments:
- The first argument allows us to add HTML before the title,
- The second allows us to add HTML after the title, and
- The third parameter determines weather the title is shown (echoed) or it is just stored for use later.
Based on this, we now understand what’s going on in line 25 of the content.php
file:
The function shows the title but we prepend an H1 starting tag to it and append the end tag.
The result of this code looks like this in the browser:
How to Level Up in WordPress Development
Chances are you don’t want to spend weeks wading through PHP documentation and learning about everything from the ground up. You should do this, but I also recommend you experiment as much as possible.
Want to move the list of tags from the bottom of the article to the top? The the_tags()
function at the bottom of the content.php
file looks promising.
First, let’s delete it together. Then, when you save and refresh the page, the tag list if gone. This is great, it means that this is indeed the function that outputs the tags. Now just copy it and paste it in to various parts of the file to see where it ends up.
it is probable that the higher up you go in the code, the higher up it will be in the article. With some experience you’ll be able to identify things like the_excerpt()
and the_content()
being responsible for displaying the content, so putting it anywhere above those will place it above the main content.
Learning how to code for WordPress this way is fun and encourages you to read the documentation, which is always a good thing. Don’t worry if you don’t understand everything – you will reach a point when you do soon enough.
Bad Practices
One drawback of this method is that you will employ bad practices. While my recommendation that you copy-paste the the_tags()
function to the top of the file somewhere works, the HTML for the footer, which uses the footer tag, will need some modification to make it good code.
Again, forget about this for now. You are not building professional-grade production-ready code for Google. You are trying to learn the basics and figure out how everything works. This is not an easy task and mistakes are part of the process.
Once you have a good working knowledge of the code behind WordPress, you can start un-learning your bad practices and you can start studying coding patterns and figuring out why we do things the way we do.
Overview Of Important WordPress Code
WordPress has a number of “subsystems” such as the loop which controls the posts shown, hooks which allow you to modify default functionality, various APIs and of course themes and plugins. I’ll give a brief introduction to some of the bigger systems you may encounter.
Enabling Debugging
By default, WordPress will hide any code errors. This is desirable in a production environment but can lead to two issues while developing. If you make a non-fatal error you won’t get any error messages and your code either won’t do anything or won’t produce the expected outcome.
The other issue is a white screen of death. No error messages, just a white screen with no more access to the front or backend. To make sure this doesn’t happen you should enable debugging, which will give you error messages.
This can be done by editing the wp-config.php
file in the root directory of your WordPress installation. Find the line which contains: define( 'WP_DEBUG', false );
and change false to true. That’s all there is to it.
Child Themes
Child themes are separate themes, which are based on a parent theme. They inherit everything from the parent theme, unless otherwise specified. This is the only safe way to modify a theme. As I mentioned earlier, the easiest way to learn is to modify an existing theme. I would like to append that with “and using a child theme.”
If you create a child theme based on Twenty Fourteen, you can still customize it to your liking but you can also update the theme without losing all your changes. This is something you should also keep in mind when working with clients. Always – always – use a child theme.
Creating a child theme is a cinch. Create a new folder in the themes
directory and name it anything you like. For our example, let’s name it “child-theme”. Inside this folder create a style.css
and a functions.php
file. Open the stylesheet and use the following to create the child theme:
You can actually use anything you like in the example above, the only restriction is the line beginning with “Template.” This must contain the name of the directory of the parent theme.
When using child themes the rule is the following: Any time a file is loaded WordPress looks for it in the child theme first. If it doesn’t exist, the same file from the parent theme is loaded. The only exception to this is functions.php
. The function files of both themes are loaded, first the child theme’s, then the parent theme’s.
At this point you can switch to your child theme but when you view your site it will be devoid of any styles. Based on our rule above it is easy to see why. The stylesheet is loaded from the child theme, since style.css
exists in the child theme, but this doesn’t contain any style information.
The next step is to load the styles of the parent theme. This can be done by enqueueing the stylesheet from the parent. Don’t worry too much about this. Feel free to copy-paste the code below into your child theme’s functions.php.
Just be aware that this loads the styles of the parent.
At this point your child theme is exactly the same as your parent theme. You can now start modifying things! You can use the stylesheet to override styles or add your additional rules. If you want to modify the index file, for example, all you need to do is create it.
If you create an empty index file then any page that would use that file will be blank. All other pages will continue to work just fine since they would use the parent theme. You can either start writing your own code into the index file or you can copy-paste the code from the parent and modify that.
The result of this should be the following: You can modify an existing theme to your heart’s content but still be able to update the parent theme or switch back to the parent theme at any time.
The Query and the Loop
The query is the system that “knows” which posts to show on a page and the loop is the part that actually goes through each post and displays them. For example, on your homepage the query looks for the 10 most recent posts. On a category archive page the query looks for the 10 most recent posts from the given category. The query is even used on single pages where it looks up a single post in the database.
The query is something you can modify and use for your own needs, but for now we’ll concentrate on the default usage, which is behind the scenes. We’ll just use the result via the loop.
The loop takes all the posts the query has returned and steps through each of them one-by-one. On some pages – like single pages – there is only one post. This still counts as a “collection” of posts – in this case the collection consists of a single post.
Let’s look at the basic code for a loop and go through it line by line:
The first line uses an if statement coupled with the have_posts()
function to figure out if there are any posts returned by the query. If there aren’t any posts, we execute the code after the else
section, which notifies the user that there are no posts.
If there are posts we use a PHP loop. There are a few types of loops in PHP. To brush up on the syntax and some more examples take a look at a PHP Loop Types tutorial.
In our code above we use a while loop, which contains the have_posts()
function again. This function returns false when there are either no posts in the loop, or no more posts in the loop since we have displayed them all.
Everything inside our while loop gets executed while the value of this function is true. This is exactly what we need. As soon as we’ve displayed the last post the value of have_posts()
will be false so the loop ends.
Inside the loop I’ve created a very rudimentary display of a post using the template tags we’ve learned about previously.
The loop should be used in any theme template file which lists posts. Search pages, single post pages, archive pages, the index file – any time you’re listing posts, use a loop!
Custom Queries
It is less common to learn about custom queries so early on, but in my experience it is one of the most sought after features in WordPress. In the section above we learned how you can list posts using the loop, but you are restricted by what is returned by default. What if you want to display upcoming related posts in the same category under a single post? This is easy with a custom query and loop.
You can create a custom query using the WP_Query
class. Classes are way above our heads now but using them is fairly straightforward. Here’s an example which shows scheduled posts from a specific category. You can use this to show a “Coming soon in this category” section.
As you can see, this is pretty straightforward. To modify this to your needs you can tweak the contents of the $args
array. There are tons of parameters you can use to restrict posts based on their publication date, based on their authors, categories, custom fields and more! Take a look at the WP_Query documentation for a full list.
Now that we have a custom query we can use a custom loop to display the content. All we need to do is prefix the have_posts()
and the_post()
functions with the name of the variable that holds the query and an “arrow”:
Apart from using referring to our custom query using the format I mentioned above, note that I left out the else
part of the loop and I used a HTML list instead of divs. Since this loop is intended to list posts under a complete single post, I thought it would be best to not show anything if there aren’t any posts. In addition, a simple list with links should be enough here for users to click through.
Hooks
WordPress uses an ingenious system to allow you to modify core functions. If you don’t already know this let me stress it as hard as I can: under no circumstances should you modify core files. This means that you can’t edit any file which comes with WordPress by default.
I know that sometimes it seems like it is the only way but it is never the case. Everything you could possibly need can be done with hooks or other methods. Modifying core files is not only dangerous but anything you do will be overwritten by an updated version of WordPress.
Hooks allow you to modify how WordPress works. They come in two flavors: actions and filters. Actions allow you to run a function of your own in specific places in the WordPress code. For example, by using a hook you can execute one of your own functions when WordPress publishes a post. This allows you to notify the author, for example.
Filters allow you to modify data before it is used. For example, you could use a filter to modify the text shown to the user when a post is saved. Instead of “Post draft updated,” you could modify this to say “Your draft has been saved.”
A great example of an action hook is wp_footer
. This action is performed just before the closing body tag of a theme. It allows you to add your own stuff to the bottom of a theme without needing to modify the theme’s footer file itself. In your theme’s functions.php
you could use the following to add a tracking code to your site:
The first line tells WordPress that we would like to add our my_tracking_code()
function to the wp_footer
hook. When WordPress loads a page and sees the wp_footer
hook it looks up all the functions tied to it and executes them. Our function then adds the Google Analytics tracking code to the footer.
This provides the basis of how plugins work. If you would create a plugin and paste the same code in there you wouldn’t need to modify your theme at all. What this means is that even if you change your theme your Google Analytics code will continue to work seamlessly.
To show you how filters work, let’s modify the content of a post with one. The the_content()
filter is run before the content of a post is shown. If we use a hook to tie a function to it we can modify it.
The code below adds the text “Checked by” automatically after each and every single post (or more accurately, any time the full post content is shown).
Note that this time the function received a parameter. Each filter and action can have one or more parameters. You’ll need to check the documentation to see what the specific hook you’re using can do. For a list of actions and filters I recommend the Actions Reference and the Filter Reference or Adam Brown’s WordPress Hooks Reference.
Further Reading
There is a whole lot you can learn about WordPress and a massive body of knowledge available for free. I’ve gathered a few resources for you and categorized them. I hope you find these useful. If you stumble across a particularly great website please do share in the comments below.
WordPress Documentation
Full Courses
- Codecademy – Codecademy have interactive classes for a number of languages
- Treehouse – Amazing videos on a variety of coding related topics
- Tuts+ – Great courses on a number of different topics
Learning About PHP
- PHP Manual – Official PHP documentation
- Codecademy – Interactive full PHP Tutorial
- W3Schools – Great complete PHP tutorial
- Tizag – Another comprehensive PHP guide
- PHP Books – Great PHP books, I especially recommend O’Reilly and Apress books
HTML, CSS and Javascript
- W3Schools – W3Schools has full tutorials to all these languages plus a lot more
- Amazon Books – Amazon has loads of books on each language or all three at once
- HTML 5 Doctor – A great place to learn about new tags and the subtleties of HTML5
Getting Help
- WPMU DEV Forums – Our forums are a great place to ask for help!
- Stack Overflow – Very popular coding related forum
- WordPress Support Forums – Official WordPress forums
Advanced Topics
- Sass – CSS with superpowers
- LESS – CSS with support for variables and functions
- OOP PHP – Object Oriented PHP
- SQL Tutorial – Learn how to query the database yourself
- Laracasts – Modern PHP and Laravel Tutorials
- Koala – Free, cross platform code compiler
- Prepros – Premium, cross platform code compiler
- CodeKit – My favorite OSX code compiler
- Grunt – Free, terminal based code compiler