Skip to content

The Essential WordPress Tutorial for PHP Developers

In this WordPress tutorial for PHP developers, we’ll look at how to start developing WordPress websites if you’re new to WordPress but already understand PHP.

So if you have a PHP background—maybe from an app framework like Laravel or Symfony—but don’t know how WordPress works, this article’s for you. (If you’re new to PHP, our free course will teach you the basics.)

WordPress for PHP Developers: the Good News

A PHP developer has a huge advantage entering WordPress, because PHP is the heart of WordPress. You just need to learn the WordPress way of doing things.

If you’re a seasoned PHP developer entering the WordPress ecosystem, you have a huge advantage, because PHP is the heart of WordPress. You just need to learn the WordPress way of doing things. In this article, we’ll outline the best jumping-off places in WordPress for PHP developers, so you can get to coding confidently as quickly as possible.

Before we dive in, you should know that this article is just a small preview of our flagship guide to WordPress development, Up and Running. If you’re serious about learning WordPress development, Up and Running is the best WordPress resource available.

Serious About Learning WordPress Development?

Get Up and Running Today

Up and Running is our complete “learn WordPress development” course. Now in its updated and expanded Third Edition, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.

 

I think anyone interested in learning WordPress development NEEDS this course.

Before I purchased Up and Running, I had taught myself some WordPress code, but lacked direction. Watching the course’s videos was like a bunch of lights being turned on.

I went from being vaguely familiar with how themes, functions and WordPress itself worked to mastering these. Everything became much clearer.

I very happily recommend this course to anyone willing to listen.”

–Jason Robie, WordPress developer

Take the next step in your WordPress development journey!

Now, let’s start with something you’ll definitely want to know as soon as possible: what WordPress is at a high level.

WordPress for PHP Developers: WordPress is a Factory

You can best understand WordPress as a factory. Specifically, it’s a factory that produces webpages.

WordPress is a Factory: A Technical Introduction

Here’s how the factory parts correspond to elements of a WordPress install:

  • Firstly, our factory site is the web server. WordPress works well on Apache or Ngnix servers.
  • The raw materials for building our finished product are posts. What are posts? We’ll come to that very shortly.
  • Our warehouse is a database which stores our posts. WordPress uses either MySQL or MariaDB databases.
  • The assembly line for putting posts together is a theme. Theme template files gather post data and control its display logic.
  • Sometimes we need to call in outside contractors to shape our product: these are plugins.
  • Finally, our end product is a finished web page.

If you use this “factory analogy” in your overall understanding of WordPress, you’ll have a very clear overall sense of what WordPress and its major subsystems are designed to accomplish, and how they work together.

WordPress for PHP Developers: Topics We’ll Cover

As a backend (PHP-based) WordPress developer, your primary job will be to create, modify, and troubleshoot themes and plugins. To do this, you’ll need to understand the following:

  • What a Post Is
  • Themes and theme Development
    • The Loop
    • The template hierarchy
    • Anatomy of template files
    • The functions.php file
  • Hooks
    • Action hooks
    • Filter hooks
  • Custom Data Types
    • Custom post types
    • Custom fields
    • Custom taxonomies
  • WP_Query
  • Plugins and Plugin Development
    • Writing your own plugins

These are the topics we introduce in this WordPress PHP tutorial. Let’s get started by learning about posts.

WordPress for PHP Developers: What a Post Is

The next step of our WordPress tutorial for PHP developers is to know what exactly a post is. When WordPress is installed, it creates 12 database tables.

database tables in a new WordPress install
Database tables in a new WordPress install

The wp_posts table is the one that PHP does most of its fetching and carrying of data to and from. Each item in the table is a post. “Post” originally meant “blog post,” as WordPress began as blogging software.

But as WordPress evolved, there was a need for content that wasn’t dated and didn’t change often. In WordPress 2.0, the page was born when a post_type field was added to the wp_posts table. This meant that it could store posts or pages.

Post types post and page in a fresh install of WordPress

Posts and pages aren’t the only content types that WordPress uses. There are also revision, attachment, and navigation menu post types.

You can even create your own types by making custom post types, like Products. We’ll return to this topic later.

WordPress for PHP Developers: Themes and Theme Development

A WordPress theme is responsible for getting the post content from the database and outputting it for display.

Only one theme can be active on a site at a time. However, it is possible to develop a child theme which inherits most of its properties from a parent theme, but is customized to appear differently on the front end.

WordPress Child Themes: A Complete Guide to the Core Concepts

A theme’s job is to dictate the appearance of the web pages it helps to generate. If a theme developer starts adding too much functionality into a theme, such as registering a custom post type, it becomes impossible for a user to switch to a new theme later without losing that functionality. We call this “theme creep.”

The Menace of WordPress Theme Creep

Put any functionality related to the site’s underlying data—rather than to presentation—into plugins, not in your theme.

The correct approach is to put your custom functionality—anything related to the site’s underlying data rather than to presentation—into plugins, which can work with any theme. Have a read through other things your WordPress theme shouldn’t do.

The minimum number of files that a theme can have is two: index.php to fetch posts, and style.css to style the output. In practice, though, most themes have many more.

WordPress Theme Development: the Loop

Within the index.php file of a theme is what is known as the Loop, the code for outputting posts.

Understanding The Loop: WordPress’s Way of Showing Posts

Here is a basic version of the Loop:

<?php
if ( have_posts() ) {
	while ( have_posts() ) {
		the_post();
		// (Loop contents will go here)
	} // end while
} // end if

First, the Loop looks in the database for posts. If there are no posts, a theme might display a message such as “Sorry, no posts were found.”

If there are posts, WordPress uses a while() loop to iterate through them. The function the_post() gets the next post ready for processing.

When all posts have been processed, the while() loop ends and the if-statement ends.

So, what does the loop actually output? It depends on the WordPress functions you add.

  • <?php the_title(); ?> displays the post title.
  • <?php the_excerpt(); ?> displays the post excerpt, a shortened version of the post.
  • <?php the_content(); ?> displays the post content in full.
  • <?php the_author(); ?> displays the post author’s name.
  • <?php the_date(); ?> displays the post date. This function uses the PHP date format.

You’ll find all these functions in the WordPress Code Reference. As you learn WordPress development, you’ll find this is an invaluable guide. Bookmark it!

WordPress Theme Development: The WordPress Template Hierarchy

Themes typically have many PHP files because they need different ways to display different types of content. And most of these files use the Loop.

For example:

  • A blog page which shows a number of posts: home.php or index.php
  • A single post: single.php
  • A page: page.php
  • A category page: category.php or archive.php

How does WordPress know which template to serve up? WordPress goes through a flowchart asking what type of content it is. It looks for the most specific template first, then falls back to something more general if that can’t be found. As a final fallback, it will use index.php.

This is known as the WordPress template hierarchy.

WordPress Template Hierarchy Explained

You can see a visual representation of the WordPress template hierarchy below, or at our site wphierarchy.com.

WordPress template hierarchy

Anatomy of template files

You will be familiar with using PHP require and include syntax for reusable code blocks.

WordPress has its own functions to include the header and footer on posts and pages:

get_header();

get_footer();

The get_template_part() function

Another important function to avoid code repetition is get_template_part().

WordPress’s get_template_part() function: What and Why

What’s cool about this function, making it superior to a PHP require or include, is that it takes multiple parameters. This means that you can have a fallback template part if the one you specify can’t be found.

In Twenty Nineteen theme a template can specify content for a specific type such as a single post (content-single.php). The content.php file is the fallback.

Twenty Ninteen content template parts

Here’s the code which calls the content-single.php template part from single.php. This line is within the Loop, after the_post();

get_template_part( 'template-parts/content/content', 'single' );

You can read more about get_template_part() here.

WordPress Theme Development: The functions.php file

The functions.php file is a specific file in a WordPress theme that contains functions which specify the theme’s setup.

Adding Functionality with functions.php, a Heart of WordPress Theme Development

These functions could include:

  • Specifying custom image sizes that the theme uses.
  • Enqueuing scripts or styles.
  • Adding navigation menus.

As we mentioned before, when you build a theme, we don’t recommend adding too many functions to it. Consider writing a plugin instead.

WordPress for PHP Developers: Hooks (Actions and Filters)

Now we come to a key part of our WordPress development tutorial: WordPress hooks.

https://wpshout.com/course-complete-introduction-wordpress-hooks-system/

Understanding how hooks work is important for writing themes, and particularly for plugins. More broadly, almost all WordPress development involves the constant use of hooks; they’re an absolutely core part of

Hooks are an event-driven system that is used throughout WordPress.

There are two types of WordPress hooks: action hooks and filter hooks.

  • Action hooks are spots in code where some functionality is added in.
  • Filter hooks modify content which is already there.

To make use of these hooks, you write functions.

Action functions (or actions) connect with action hooks, and do not return a value.

Filter functions (or filters) connect with filter hooks and must return a value.

WordPress Hooks: Action hooks

An example of an action hook is widgets_init.

Many plugins use this hook to add a widget to the default list. Widgets show on the front end in widget areas, often sidebars.

Here’s an example of an action function that makes use of that hook.

add_action( 'widgets_init', 'First_WordPress_Widget');
function First_WordPress_Widget(){
	register_widget( 'First_WordPress_Widget' );
}

The widget must be defined as an extension of the WP_Widget class. For that, you need a constructor function and another to show widget content on the front end. If you have used object-oriented PHP this code will look familiar.

/**
* Adds First_WordPress_Widget widget.
*/

class First_WordPress_Widget extends WP_Widget {

	/**
	* Register widget with WordPress.
	*/
	public function __construct() {
		parent::__construct(
			'First_WordPress_Widget', // Base ID
			'First WordPress Widget', // Name
			array( 'description' => __( 'First WordPress Widget', 'text_domain' ), ) // Args
		);
	}

	/**
	* Front-end display of widget.
	*
	* @see WP_Widget::widget()
	*
	* @param array $args     Widget arguments.
	* @param array $instance Saved values from database.
	*/
	public function widget( $args, $instance ) {
		echo 'First WordPress Widget! Yay!';
	}
}

Here’s how the backend looks:

First WordPress Widget - back end

And on the front end, in Twenty Nineteen theme:

First WordPress Widget - front end

While this code creates a working widget, it’s not that useful as it doesn’t accept any user input. To find out how to make user-editable widgets, head over to Fred’s tutorial on Creating Dynamic, User-Editable WordPress Widgets.

WordPress Hooks: Filter hooks

An example of a filter hook is excerpt_length.

The function below makes use of that hook by reducing the default excerpt length from 55 words to 25 words:

function custom_excerpt_length( $length ) {
	return 25;
}

add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

The 999 indicates priority. Any action or filter with a priority of 999 will run after any other functions attached to the same hook.

WordPress for PHP Developers: Custom Post Types, Custom Fields, and Custom Taxonomies

Let’s extend this WordPress tutorial for PHP developers to discuss WordPress’s main custom data types: custom post types, custom fields, and custom taxonomies.

Custom Post Types

Custom post types, often abbreviated to CPTs, are a powerful feature in WordPress. Using them you can create any content type you desire. Like posts and pages, CPTs are stored in the wp_posts table.

Why and How To Use Custom Post Types in WordPress

Custom Fields and Custom Taxonomies

Custom fields and custom taxonomies are distinct ways of adding additional data to WordPress posts.

Using Custom Taxonomies and Custom Fields in WordPress Development

Custom Fields

Custom fields are metadata that you can add to any post type. They are stored in the wp_postmeta table in your WordPress database and consist of a key (or name) and a value.

You can use the get_post_meta()function to output values from your custom fields. See how in David’s article, How to Create and Use WordPress Custom Fields.

How to Create and Use WordPress Custom Fields

Custom Taxonomies

Taxonomies are ways of classifying content. WordPress has two built-in taxonomies, categories and tags, which are available to posts. Categories are hierarchical, so can be subdivided. Tags are flat and have no hierarchy.

Find out how to define your own custom taxonomies.

WordPress Custom Taxonomies: How and Why to Create Them

Three related tables store taxonomy data:

wp_terms stores the names you use in your taxonomies. In this example, there are 4 shown: Men, Men’s Jeans, Men’s Shirts and Men’s Shoes.

wp_terms - WooCommerce store

wp_term_taxonomy shows the type of taxonomy for each term. In the following example, they are all product categories.

wp_term_taxonomy - WooCommerce store

wp_term_relationships shows the relationships of each taxonomy to its products. The object_id field corresponds to the ID of the wp_posts table.

wp_term_relationships - WooCommerce store

Here’s how you might use taxonomies and custom fields with a book custom post type:

  • Genre: a custom taxonomy for the type of writing. Like a category, you can subdivide a genre, so ‘Romance’ could be broken down into ‘Historical romance’ and ‘Vampire romance’ etc.
  • Author: a tag-like custom taxonomy for writers.
  • Publication date: a custom field with the year of publication.

To retrieve this information, we can use a new tool to query the WordPress database:  WP_Query.

WordPress for PHP Developers: WP_Query

WP_Query is an important part of this WordPress tutorial for PHP developers: it’s a powerful means of giving a custom order in the WordPress factory. When you use WP_Query, you can query for data—specifically, for WordPress posts—using PHP syntax rather than SQL.

WP_Query: Understand it, Love it!

In technical terms, WP_Query is a PHP class from which you can instantiate a query object.

A basic query object is formed like this:

$query = new WP_Query( $args );

When you create your query object you can pass arguments to it in the form of an associative array, with keys and values. This makes it possible to get results from extremely specific queries.

These arguments select 5 posts in the category markup and sorts them in a random order.

$args = array(
	'posts_per_page'           => '5',
	'orderby'                  => 'rand',
	'category_name'            => 'markup',
);

See the full list of WP_Query parameters.

You can use your query object both within the Loop and outwith the Loop.

When your query is finished, you should end your code with wp_reset_postdata() which resets the global $post variable to its original state.

Your final code might look like this:

<?php
// WP_Query arguments
$args = array(
	'posts_per_page'         => '5',
	'orderby'                => 'rand',
	'category_name'          => 'markup',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
	while ( $query->have_posts() ) {
		$query->the_post();
		$output = '<a href="'.get_the_permalink().'">';
		$output .= '<h2>'.get_the_title().'</h2></a>';
		$output .= '<p>'.get_the_date().'</p>';
		echo $output;
	}
} else {
	// no posts found
	echo 'There are no posts to display.';
}

// Restore original Post Data
wp_reset_postdata();

?>

Notice how get_the_title() is used rather than the_title(). That’s so the title can be stored in the $output variable rather than echoed directly. The same applies to the permalink and the date.

For more on this topic, we have a course on WP_Query which you can work through.

WP_Query: Understand it, Love it!

WordPress for PHP Developers: Plugins and Plugin Development

We’d be remiss if you read our entire WordPress tutorial for PHP developers without knowing what and how plugins work—they’re extremely important in WordPress.

Plugins are code packages that add functionality that’s not part of WordPress Core.

Plugins are code packages that add functionality that’s not part of WordPress Core. Like contractors, they only come into the factory when they’re called into use.

One of the simplest (and least useful) WordPress plugins, which is included with every new install of WordPress, is Hello Dolly. The plugin uses a mix of WordPress functions and PHP functions.

Here’s a rundown of the plugin’s functions and what they do.

hello_dolly_get_lyric()

  1. The “Hello, Dolly” song lyrics are stored in a variable, $lyrics.
  2. The lyrics are split line by line into an array using the PHP explode
  3. PHP’s count function counts the number of items in the array, and the mt_rand function selects a random line.
  4. The wptexturize() function prettifies dashes, quotes and apostrophes within the text.
  5. Finally, the function returns a value, a random line from the song.

hello_dolly()

  1. The song line from the hello_dolly_get_lyric() function is retrieved and stored in a variable, $chosen.
  2. A second variable, $lang is defined as an empty string.
  3. The get_user_locale() function gets the WordPress user’s locale (their language and region).
  4. Using PHP’s substr function to get the first 3 letters of the locale, an if statement checks if this string is not equal to the string 'en_'. In other words, is the user not using English as their language?
  5. If the if statement evaluates true, $lang is set to ' lang="en"'. Otherwise, this variable retains its empty value.
  6. PHP’s printf function outputs the two variables within some HTML. The $chosen variable is output within <span> tags. If the if statement was true, the $lang variable is added as an attribute of this <span>.
  7. A few words explaining the song and composer is inserted as screen reader text so that blind users know what the lyric represents. The words are wrapped in the WordPress translation function __(). If there is a translation available, it is output. If no translation is available, the original English text is output.

add_action( 'admin_notices', 'hello_dolly' );

This hooks into the admin_notices  action hook to add the output generated by hello_dolly() there. Because it’s an admin notice, it will only be seen when a user is logged in.

dolly_css()

This uses PHP’s echo to output some CSS code to style the lyric.

add_action( 'admin_head', 'dolly_css' );

Finally, this function hooks into the admin_head action hook. It adds the CSS style just defined into the <head> of the WordPress admin.

Here is an example of the output in English:

Hello, Dolly in English

<p id="dolly"><span class="screen-reader-text">Quote from Hello Dolly song, by Jerry Herman: </span><span dir="ltr">Hello, Dolly</span></p>

And in French:

Hello, Dolly in French

<p id="dolly"><span class="screen-reader-text">Citation de la chanson Hello Dolly, par Jerry Herman&nbsp;: </span><span dir="ltr" lang="en">I can tell, Dolly</span></p>

Writing your own plugins

To get started on authoring plugins, follow our step-by-step tutorial on writing a WordPress plugin from scratch.

Writing a WordPress Plugin From Scratch: A Step-by-Step Tutorial

It’s good practice when you are writing plugins to use namespaces, as you would when coding with PHP. Using namespaces makes your code more organized and maintainable. Find out more about namespacing in WordPress plugins.

As you saw with the Hello Dolly plugin, it’s also smart to prepare your plugins and themes for translation, so that they can reach more users. Read more about translation and internationalization functions in WordPress.

Summing up

That’s a wrap on this WordPress tutorial for PHP developers. Congratulations – you’ve now covered the essentials of how to use PHP in WordPress.

If you’re interested in becoming a fully-fledged WordPress developer, our Up and Running: A Practical Guide to WordPress Development will get you up to speed quickly. Check it out today!

The Best Way to Learn WordPress Development

Get Up and Running Today

Up and Running is our complete “learn WordPress development” course. Now in its updated and expanded Third Edition, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.

Here’s what they have to say:

wordpress freelancer caroline “Other courses I’ve tried nearly always lack clear explanations for why WordPress does things a certain way, or how things work together.

Up and Running does all of this, and everything is explained clearly and in easy-to-understand language.”

–Caroline, WordPress freelancer

Up and Running really brought everything together for me. I already knew of some of the pieces, but the course filled in the gaps and provided a proper understanding of how WordPress really works.

I found it easy to follow, delivering just the right depth of knowledge in the right sequence.”

–Hugues, freelance web developer

Yay! 🎉 You made it to the end of the article!
Claire Brotherton
Share:

0 Comments
Inline Feedbacks
View all comments

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!

0
Would love your thoughts, please comment.x