Despite what it may seem like WordPress doesn’t run on fairy dust, no — instead your WordPress website is powered by a server-side programming language called PHP and MySQL databases. 

In this guide I’ll be showing you what PHP in WordPress looks like, explaining how you can add custom PHP to your WordPress website and debunking various myths surrounding PHP in WordPress. 

Let’s get started. 

What is PHP?

PHP is a server-side programming language and despite what you may think PHP isn’t exclusive to WordPress. Rather WordPress is written in PHP but so are thousands of other applications. 

You may already be familiar with the popular “Hello World” example like this:

<html>
<head> <title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>

It doesn’t look like much but running that on your server will output “Hello World” on a page. Ok not the most exciting but bear with me. 

Where you see <?php this is the opening tag and tells the server “hey, we need to start processing some code at this point”. And then ?> tells the server “hey, for now, our code is finished”. 

Explaining PHP in depth would require a book as there’s so much to learn but don’t let that scare you! Learning to program is great fun and opens up a world of possibilities whether that’s by tweaking your own website or forging a new career path. 

Later on in this guide, we have a whole section dedicated to learning resources that you can jump to but we think you’ll be more interested in continuing to know about PHP in WordPress.

WordPress PHP — What is it? And What Does it look like?

WordPress is coded in PHP and has its own API (application programming interface) terms.  You’ll regularly come across the terms hooks, actions, filters, the loop, templates, themes, and plugins when reading about development in WordPress.

But just what are all these terms and what do they mean? 

Filters and actions (hooks)

In WordPress, there’s something called hooks. Hooks are filters and actions that allow you to either extend functionality (actions) or filter data to perform changes on the output (filters). 

To understand more about what actions and filters are and what they do, we’re going to take a look at one of the most popular plugins for WordPress, WooCommerce.

What are WordPress actions? 

Actions in WordPress are a way to add new parts to your website, plugin or theme. For example, in WooCommerce actions can be used to:

  • Add a new checkout field. 
  • Add new shipping methods. 
  • Create a new payment gateway. 

And so much more.

Let’s take a look at this example from the WooCommerce developer documentation:

add_action( 'woocommerce_admin_order_data_after_shipping_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 ); function my_custom_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('Phone From Checkout Form').':</strong> ' . get_post_meta( $order->get_id(), '_shipping_phone', true ) . '</p>';
}

As we can see this is an action that hooks into the WooCommerce action “woocommerce_admin_order_data_after_shipping_address” action and then runs a function to output an additional field for a phone number. 

Now if we take a look at the action:

add_action( 'woocommerce_admin_order_data_after_shipping_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );

We can see a 10, 1. But what is it and what does it mean?

Priority in WordPress Actions

The 10 is the priority of when the action will be executed. Think of it as getting served in a queue, the person with the lower number gets served first, the person with the higher number has to wait. 

Well, actions work in the same manner. Actions with a lower number get executed first, the default priority is 10. 

Why is it useful though? Let’s say you need a specific action to be loaded before your function can run as it interfaces with that action. Well then if the action you’re waiting on is set as the default priority (10) you can then set your action at say 15 which guarantees the other action has already been loaded. 

Arguments in WordPress

The 1 is how many arguments the function accepts that you’re writing. Need multiple arguments for your function? Then you should raise the value as needed. 

If you’re familiar with PHP at all, then you’ll already know about arguments as they don’t have any special functionality in WordPress at all. 

Want to learn more about arguments in PHP? Check out the official PHP documentation.

Loops in WordPress (WP_Query)

WP_Query is one of the most powerful and important classes in WordPress. Using WP_Query you can build a loop to retrieve posts and display them on the front-end of your site. 

Every theme has a loop that is included to get the latest blog posts for example. 

A loop can be a lot simpler than you expect. For example, here’s a standard loop in WordPress.

<?php // The Query
$the_query = new WP_Query( $args ); // The Loop
if ( $the_query->have_posts() ) { echo '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>';
} else { // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

But what are we doing here? Let’s break it down a bit. 

if ( $the_query->have_posts() )

Checks for if there are any posts to output. If not, nothing is done. If there is, we get the posts using:

while ( $the_query->have_posts() ) { $the_query->the_post();

We then echo (output) the post and get the title. 

echo '<li>' . get_the_title() . '</li>';

But what happens if we don’t have any posts? Then nothing happens and nothing is output. Most themes add additional code after the else statement to echo a message such as “no posts have been found”. 

For example, here’s an alternate loop with that output:

<?php
// the query
$the_query = new WP_Query( $args ); ?> <?php if ( $the_query->have_posts() ) : ?> <!-- pagination here --> <!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop --> <!-- pagination here --> <?php wp_reset_postdata(); ?> <?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Want to learn more about WP_Query and what it can do? Check out the official WordPress Codex. 

PHP in WordPress Themes 

We’ve already explored the WP_Query class above which makes up one of the most important aspects of any WordPress theme. 

But there’s also so much more involved in a theme. At a minimum, a theme needs a stylesheet to be able to be activated. For example, here’s the style.css of the default TwentyTwenty theme:

<?php
/*
Theme Name: Twenty Twenty
Text Domain: twentytwenty
Version: 1.5
Requires at least: 4.7
Requires PHP: 5.2.4
Description: Our default theme for 2020 is designed to take full advantage of the flexibility of the block editor. Organizations and businesses have the ability to create dynamic landing pages with endless layouts using the group and column blocks. The centered content column and fine-tuned typography also makes it perfect for traditional blogs. Complete editor styles give you a good idea of what your content will look like, even before you publish. You can give your site a personal touch by changing the background colors and the accent color in the Customizer. The colors of all elements on your site are automatically calculated based on the colors you pick, ensuring a high, accessible color contrast for your visitors.
Tags: blog, one-column, custom-background, custom-colors, custom-logo, custom-menu, editor-style, featured-images, footer-widgets, full-width-template, rtl-language-support, sticky-post, theme-options, threaded-comments, translation-ready, block-styles, wide-blocks, accessibility-ready
Author: the WordPress team
Author URI: https://wordpress.org/
Theme URI: https://wordpress.org/themes/twentytwenty/
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html All files, unless otherwise stated, are released under the GNU General Public
License version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned
with others.
*/

The most important parts are the theme name and the theme version which tell WordPress what the theme is called and what the current version number is. 

The Requires at least tag is used to specify the minimum WordPress version required to run the theme. This prevents someone with an old install of WordPress from installing the theme. A new theme may not run correctly on old versions of WordPress.

But of course, you need other files to actually show content and display content. But how do you know what’s needed?

Luckily WordPress has what’s called the template hierarchy, this is used by themes and plugins to help specify what template file should be loaded for displaying that content. It can seem daunting at first but study the diagram found here and it’ll soon make sense.

Developing a theme from scratch is a time-consuming affair with often hundreds of hours involved. There can be tens of hours spent in just setting up the main template files and your development environment. 

Not to mention there’s also the time you need to make sure your theme is developed to the WordPress coding standards. 

That’s where theme frameworks come in. Frameworks are like building blocks to help you create your end product quicker. There’s a variety of frameworks available, all of varying quality. Some good, some not so good. 

In addition to theme frameworks there are starter themes. Starter themes are themes that already work but are designed to be modified and then redistributed. One of the most popular starter themes available is underscores. 

Here are our top 2 frameworks for getting started with theme development. 

Top 2 WordPress Theme Frameworks

Sage

Sage is a modern WordPress starter theme/theme framework utilizing webpack to automatically watch and build assets along with support for SAAS out of the box. 

If you’ve ever used Laravel you’ll be pleased to know that Sage uses Laravel’s Blade templating engine. Although Blade is a great templating engine, it strays outside the WordPress remit. Fine if you’re already a WordPress expert. But for beginners, it could muddy the waters. 

Like most starter themes and frameworks, Sage is free and comes with well-written, well- thought-out documentation. 

Underscores 

We’ve already touched on Underscores before but it should be mentioned again. Without a doubt, Underscores is one of the best starter themes to kick-off your WordPress theme development project. 

It’s well-thought-out and comes with all the needed templates to get you started. Along with CSS for mobile ready navigation, Underscores makes building a WordPress theme a pleasure. 

Contributed to by some of the brightest minds in the WordPress community and fully open-source, it’s definitely something you should consider for your next project. 

PHP in WordPress Plugins 

PHP in WordPress plugins works the same way as PHP in WordPress themes. With the exception that most plugins wouldn’t use the loop.

But they do make use of actions and filters like we explored in some of our previous examples. 

Plugins can be made to do nearly anything your mind can think of and are commonly built to connect third-party APIs with WordPress. An example is Zapier plugins, a plugin that helps you automate an array of tasks on your website. 

Just like themes, there are starter plugins that you can use to make sure your plugin has a coherent structure to it (please don’t put everything in a single .php file). 

Structure wise, the only file a plugin needs to work is a single php file. This file can be named anything you want but as with themes, the name of the plugin should come from the plugin header file, which looks like this:

<?php
/**
* @package Hello_Dolly
* @version 1.7.2
*/
/*
Plugin Name: Hello Dolly
Plugin URI: http://wordpress.org/plugins/hello-dolly/
Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
Author: Matt Mullenweg
Version: 1.7.2
Author URI: http://ma.tt/
*/

The plugin name is what you see in your wp-admin > plugins. 

When building your plugin, keep in mind it doesn’t need to be complex or do lots of things. In fact, the best plugins are those that are focused towards doing one thing and doing it well. 

Plugin starter kits are usually called boilerplates. And unlike themes, there aren’t many options available. Due to the rapid pace at which WordPress develops, most boilerplates are developed and then no longer maintained. It takes a considerable amount of time to update a boilerplate. 

One of the best boilerplates available is WordPress Plugin Boilerplate.

Where to Learn WordPress PHP

Before you deep dive into learning the WordPress way of doing things, you should familiarize yourself with PHP in general. This will make learning WordPress PHP easier and won’t have you hitting your head against the wall anywhere near as much. 

Assuming you already know general PHP, here are our favorite resources for learning WordPress PHP. 

  1. TutsPlus — TutsPlus (by Envato) has a string of high-quality WordPress PHP tutorials including this course by Rachel McColin. In addition to the courses, there’s high-quality content on their blog from well-respected developers in the WordPress ecosystem, such as Pippin Willamson of SandHills Development (Easy Digital Download, AffiliateWP). 
  2. WPShout — WPShout is the premier blog for WordPress developers, from beginners to advanced users. There’s something for everyone. The tutorials are both well written and comprehensive, always ensuring you learn something. 
  3. WP Codex — It goes without saying but the WordPress Codex is a fantastic resource to learn everything you need to know. It can seem daunting at first, given the amount of information available. Take your time and go through it slowly and you’ll find a wealth of useful tutorials and guides to help you learn WordPress PHP. Along with references for all filters and functions. 
  4. Scotch.io — Scotch has a range of tutorials and isn’t WordPress specific, but has great tutorials for React, Javascript, and more. They also have some fantastic tutorials on building WordPress plugins and themes. Definitely worth a look for any aspiring developer. 

WordPress Developer Resources

Along with the resources we mentioned above for learning WordPress PHP, it’s also worth checking out the fantastic book Professional WordPress Plugin Development. 

And of course, who can forget StackOverflow, the developers’ version of Google. If you’re having an issue you can’t solve, StackOverflow most probably has the answer. Check out the WordPress tag for example to find an array of questions specifically related to WordPress development.

Debugging in WordPress 

WordPress makes debugging relatively straightforward. There’s the define WP_DEBUG which can be added to your wp-config.php and set to true to show any warnings, notices or errors. 

To enable just add:

define('WP_DEBUG', true);

And then you’ll see any issues in the admin area and front-end of your site. Although it’s recommended to output the notices, warnings, and errors to a log and hide the display on the front-end. 

So for that you can add to your WP-config.php directly below WP DEBUG:

define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

This will create a debug.log file in your wp-content folder and also prevent debug messages from outputting on the front-end or admin side of your website. 

It’s important to note you shouldn’t leave WP_DEBUG set to true in a live environment. Sometimes it may be necessary to enable it to hunt down a problem you’re having. As soon as said problem is solved, you should set it back to false. 

There’s more to debugging in WordPress than WP_DEBUG. There’s also a wide variety of tools and plugins created by the community to make debugging in WordPress easier than ever before. 

One of my personal favorites is Query Monitor.

Taken directly from the plugin description, Query Monitor is the developer tools panel for WordPress. It enables debugging of database queries, PHP errors, hooks and actions, block editor blocks, enqueued scripts and stylesheets, HTTP API calls and more.

It really is the ultimate developers toolkit and if you’re stuck trying to find out why something isn’t working correctly, the Query Monitor is a vital tool to hunt down that pesky issue. 

Development IDEs for WordPress Developers

An IDE is an integrated development environment and is used by hobbyists and professional developers alike to build and develop their latest and greatest projects. 

Nowadays many IDEs have built-in WordPress support for code formatting, auto-completion and more. 

Some of the most popular IDEs among the WordPress community include: 

PHP Code Management in WordPress

What good is writing all this code if it’s just strewn across your laptop and not stored or managed anywhere? 

That’s where GIT comes in. The most popular GIT based management tool is GitHub, an easy to use platform for managing code including creating branches, pull requests and working with collaborators. 

It is critical that you commit code often, and with commit messages that make sense, when managing your project. It will make it much easier to revert a commit when something breaks, rather than having commit messages like “this update is good”. 

WordPress itself, if you host a project on the WordPress.org repository (be it a theme or a plugin), still uses SVN. 

It’s the bane of developers lives everywhere, often slow to update and reflect changes and not overly intuitive to work with. 

The most popular SVN GUI (graphical user interface) tools are Tower for Mac and TortoiseSVN for Windows-based machines. 

Wrapping Up

Getting started with WordPress development can be one of the best decisions you ever make. With a growing ecosystem and market share going up year upon year, it’s certainly not a bad skill to have.

Our guide can only touch on all of these points of PHP WordPress development. Otherwise we’d be writing a book! (now there’s an idea) But hopefully, you’ve learned a thing or two and have checked out the extra resources we’ve rounded up. 

How far along are you in your WordPress development journey? Have any tips for aspiring developers to be? Let us know in the comments below. 

Spread the love

Posted by News Monkey