So far in this series we’ve talked about some tools and best practices, HTML and its new big brother HTML5 as well as an overview of how to work with CSS. In this post we are going to take a look at PHP basics.
Like so many things in the internet world, PHP is an acronym. It stands for “PHP Hypertext Preprocessor.” (I know. It makes no sense that the first P in PHP stands for, um, PHP. But there you go.)
PHP is the primary programming language WordPress is built on. That means it is also the primary programming language for the Genesis theme framework. Therefore if you want to start customizing child themes then it’s a good idea to start to learn a little PHP along the way. It will open up so much more for when it comes to real power to add/remove/move blocks of content when customizing your Genesis child themes.
Powerful and Empowering
I’ll tell you right now, this is where the rubber meets the road, so to speak. Being able to work with CSS and HTML is certainly a requirement when it comes to customizing themes. But having a working understanding of how PHP works and being able to make changes to a theme’s PHP files will really set you apart.
Just know working with PHP is a little more technical than CSS or even HTML. Because it is so powerful you can break your site in a hurry when editing PHP files. All it takes is a missing semicolon or a closing bracket in the wrong place and that one little character can bring your whole site crashing down.
That’s why I recommend the work flow I covered in the previous article in this series, Workflow for Customizing Genesis Themes. The way I recommend makes recovering from mistakes simple.
And being able to easily recover from mistakes is especially important when working with PHP files.
So let’s dive into PHP basics.
Basic PHP Syntax
Like most computer languages, PHP has a defined structure and syntax for writing the code.
The first thing you’ll want to know is that like with CSS and HTML, PHP files are plain text files. The main difference is that PHP files end with the .php file extension. This tells your web server to process the file via PHP.
PHP code is further wrapped with an opening <?php and closing ?> tag, which means that we can mix PHP and HTML within the same file.
Having that ability makes for a very powerful combination. We can use HTML for our presentation and at the same time use PHP to do things like reading and writing to the database, decisional logic, accessing other component files, etc.
Comments In Our Code
Comments are important for our code because they allow us to communicate what we are doing with a piece of code. While it’s nice to let others know what the code is doing, WordPress is open source after all, it is even more valuable to ourselves when we come back to that code moths later.
Before I got into the habit of commenting my code I had several times where I was scratching my head wondering, “what was I trying to do here?” Good commenting is one of those things that takes a small investment of time on the front end to save a ton of frustration later on.
Comments can be added to PHP in two different ways.
First you can comment out a single line of code with a double slash // at the beginning of the line. Those comments look like this:
<?php // This is a comment PHP code goes here ?>
You can also have multiple lines of comments. Start your comment block with a slash and an asterisks /* and close it with the reverse */ to end it. Those comments look like this:
<?php /* This is a comment block. It will keep going until we close it out. */ PHP code goes here ?>
PHP will ignore everything between those two tags, even if it is PHP code! That means in addition to annotating your code, a useful customization trick is to comment out sections of code that you wish to disable instead of deleting the code. Then if something ever changes and you need to restore the code you just have to delete the comment marks and your code is restored.
Otherwise you need to go hunting for a backup version of your theme to find what that code was you deleted way back when. Trust me, that takes far longer than deleting a couple comment tags.
Functions
Much of the power of PHP is organized inside functions. Functions are modular blocks of code. Here’s an example of a basic function.
function wsm_add_viewport_meta_tag() { echo '<meta name="viewport" content="width=device-width, initial-scale=1.0"/>'; }
As you can see, functions start with the word “function”. Next is the name of the function itself followed by a set of parenthesis. Then we have a set of curly brackets which is where the action happens inside the function.
Calling Functions
There are basically three ways you can call a function. We can call the function directly by using the function name itself. Using our example above we can call our function by using it’s name like this:
wsm_add_viewport_meta_tag();
In the Genesis theme framework we use this approach in our child template files when we call the genesis(); function to tap into the framework.
Usually functions are called by actions and filters though so we can target exactly where they’ll apply. We’ll have posts later in this series explaining how those two work. But know that a function is only processed when it is called.
Function Names
Function names cannot repeat so two functions with the same name will cause a fatal error and crash your site. None of the function names can repeat throughout your entire site, including your theme files and all the plugins activated on your site.
So when customizing it is a good practice to add a prefix to your functions names to keep them unique. If you look through the code in our themes you’ll see that we use wsm_ at the beginning of our functions for this reason.
The All Important Semicolon
Notice also that the line of code inside the function ends with a semicolon. It’s easy to say that the statements inside your functions each need to have a semicolon at the end.
However for some reason it’s an incredibly easy thing to miss, especially when just getting started with theme customization. In my early days I lost hours and hours troubleshooting problems that turned out to be missing and misplaced semicolons. (My worst was two days of frustration for a problem that was instantly fixed when I found I was missing a semicolon.)
It doesn’t take many times of that sort of thing happening before you remember to pay attention to your semicolons.
For what it’s worth, the other big got’cha I see is missing the closing bracket for the function. Because functions can be nested it’s important to match up the opening and closing brackets. One of the benefits of using a quality code editor like one of the ones mentioned in our previous post about tools for customization.
PHP Variables and Arrays
With PHP we can pass data with variables and arrays. For example in the function where we customize the post by-line below the post title with the Genesis framework we assign a post info variable like this:
$post_info = '[ post_date] by [ post_author_posts_link] [ post_comments] [ post_edit]';
We can adjust this variable to pass the shortcodes we want to use for our theme and display.
PHP variables start with a dollar sign. The next character must be a letter. Variables can be a mix of letters, numbers and underscores. Within those parameters variables can be anything you want them to be. Keep in mind variables are case sensitive too. So $Post_Info is not the same as $post_info.
PHP arrays are used to pass a set of related data. For example when we register widget areas in the Genesis framework we use an array like this:
genesis_register_sidebar( array( 'id' => 'rotator', 'name' => __( 'Rotator', 'wsm' ), 'description' => __( 'This is the image rotator section.', 'wsm' ), ) );
Arrays can be assigned to variables as well.
PHP Conditional Logic
We can use conditional statements inside our functions to only do things when we want them done. That might look something like this.
function wsm_example_conditional() { if ( some conditional test ) { do some stuff } elseif ( another conditional test ) { do something else } else { do yet another thing } }
WordPress has tons of functions, many of which we can use for conditional tests.
Also PHP has a bunch of operators we can use in our conditional statements as well.
So you begin to see how we can stitch together variables, arrays, functions, conditional statements and operators to start putting together our theme customizations.
Resources
There are a couple resources that are incredibly useful when customizing your Genesis child themes.
StudioPress has a very useful list of Code Snippets. One of the nice things about using the Genesis theme framework is that most times we can use the same functions in different child themes to do the same things. That way we don’t have to reinvent the wheel when customizing our themes.
Another very useful resource for functions and code we can use in our themes is the WordPress Codex.
Between these two and a little bit of Google searching, there’s plenty of code out there to get you started in your customization.
This is the ninth in our series of articles on Best Practices for Genesis Theme Customization.
Theresa Wagar says
Great intro to PHP. I thought your best point was about commenting your code. I thought I was the only who scratched my head and wondered what in the world I was thinking when I wrote that code . ..LOL. I also use comments often to deactivate code just in case.
I’ve learned PHP over the past few years through trial and error (I do have some coding background, but I’m not sure FORTRAN even counts anymore . . .LOL). Cutting and pasting other people’s code (especially the code snippits) really helped me understand how PHP worked within Genesis and WordPress.
Thanks for laying out the basics. I know others new to PHP will save time in their learning curve by reading this.
Theresa 😎
Chris Cree says
Heya Theresa!
We’re dating ourselves even admitting we know what FORTRAN is. 😉
Commenting out code is a useful tool, for sure. I also will comment out code when troubleshooting things too. If something’s misbehaving I’ll start commenting out functions to isolate the problematic code. That helps me narrow down the problem quickly and resolve issues more quickly than deleting stuff. Plus I won’t forget what that code was either so I can easily restore it.
Mary says
Hi Chris,
I am working with Genesis and trying to understand their PHP files so I can create a child theme. It seems that the ending PHP code is supposed to be: ?>
but every one of the Genesis PHP files has a ; as the final code in the file. I am not seeing ?> anywhere.
Can you “end” a PHP file without ?>
Thanks,
Mary
Chris Cree says
Heya Mary!
When I first started working with WordPress most all theme files each ended with a closing ?> tag. We’d get in trouble when files had extra characters like spaces and line returns in the .php files after that last closing ?> tag. Many of us spent hours (and hours, and hours, and days) troubleshooting sites that had a theme or plugin file with extra (basically blank and hard to see – especially if you aren’t using a text editor that has line numbers) stuff after a closing tag somewhere.
But no, to answer your question it isn’t required. PHP doesn’t require the closing tag, and since leaving it off the ends of files eliminated all of that sort of hassle, we got into the habit of leaving them off, pretty much across the board. If you look at the files in the current WordPress install package from WordPress.org you’ll see that they don’t have the closing PHP tags in those files either.
Honestly I don’t know if the more recent versions of PHP still have those same sensitivities to extra non-visible characters after the closing PHP tag as before. But I’ve wasted far too many hours hunting down these kind of issues in the past to even want to test it and find out.