WordPress Development | WordPress: A Closer Look


 

The official WordPress logo, in all its glory. In this lecture, we will explore the basics of WordPress and how to install it for your own site.

At the end of Lecture One, we focused a bit on WordPress and it being more than "just a blog." Now it's time to prove that!

Throughout the rest of this course we will dive deep into WordPress, exploring everything it can do and building out a full site using it.

My goal is to convince you that WordPress is powerful and versatile enough to meet any challenge a Web design client might bring you, and I want to teach you enough about WordPress that you feel fully confident offering up your expertise whenever a client needs a CMS.

In this lecture, you can expect to:

Learn how to get started with WordPress.
Explore basic WordPress features, including posts, pages, and widgets.
Learn how themes and plugins expand WordPress functionality.
Learn how to install WordPress on a server.
Explore the settings of a hosted WordPress site.
Review tutorial resources for PHP.

 

 

 

 

 

 

 

 

 

 

 

 

Both the hosted and downloaded versions of WordPress are 100% free.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Posts and pages can be a little confusing to keep straight. To help yourself out, remember that posts are dynamic and pages are static.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

A slug is the URL friendly version of the title. A custom post type called "Contact List" would have a slug of "contact-list".

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Properly built widgets can be arranged anywhere on your site.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Themes control the look of your WordPress site.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The WordPress Codex is the top source if you need to know something about WordPress. You can access it at codex.wordpress.org.

 

Getting Started With WordPress

Finding Your Way Around

You can get started with WordPress in a few clicks. For the first part of this lecture, we'll get to know the WordPress interface through a WordPress.com blog. Then we'll move onto a downloaded WordPress.org site. The basics of the user-facing administration tools is pretty similar for both, and it's faster to begin with WordPress.com, so we'll start there.

Go to WordPress.com and click Get Started:

Follow the prompts to set up a WordPress.com blog. Make sure you select the free option! As you'll discover, all of WordPress—both .org and .com varieties—is free. WordPress does offer premium options, but if you already have hosting and a domain name, you don't need them.

Once you're set up, you'll be taken to the My Blogs screen. From here, click Dashboard to get into the WordPress admin panel:

The Dashboard is where all the action happens: adding posts and pages, changing settings, choosing and editing themes (we'll discuss themes a little later in the lecture), configuring users, and more. What we won't be doing with PHP, HTML, and CSS in source files, we'll be doing with the WordPress dashboard.

The WordPress Dashboard is your control panel for all of WordPress! What doesn't happen directly in the code happens here on the Dashboard.

WordPress offers a great short video tour to get you familiar with the Dashboard. Watch it now to get acquainted.

Now that you're in the Dashboard and ready to go, let's begin our own tour of WordPress's features. Things are a little different depending on whether you're just a user or—like us—you're a developer. We'll be exploring WordPress from a developer's perspective. Let's get started!

Features of WordPress

WordPress is packed with features to help you quickly and easily get a site online. In this lecture we'll look at the core features, starting with creating content.

Posts, Pages, and Custom Post Types

There are three main content areas: posts, pages, and custom post types. The first two are built into WordPress. Custom post types you will have to program or use a plugin for (which I'll show you how to do).

Posts are your regularly updated, blog-style content sections that are displayed several to a page in reverse-chronological order. Posts are akin to blog posts. Pages, on the other hand, are generally longer, with content that is "static," or not updated very often.

However, when we get into talking about custom post types (CPTs), we have to backtrack a little. While it's true that we can think of posts with their more familiar blog-style definition, it's important to note that on the back end, any content in WordPress is considered a "post." This includes:

 
 
  • Posts

  • Pages

  • Attachments (images and other media)

  • Revisions

  • Nav menus

 
 

So when is a post not a post? When it's a custom post type. Custom post types (CPTs) allow us to create our own posts with their own set of data fields. For example, where a post has a title, description, category, and slug, a CPT for a business might have a title, description, category, slug—and more! Like fields for an address, city, Web site, and phone number. CPTs allow us to create more "metadata" for better, more usable, searchable content. A better, less confusing name, might actually be "custom content types."

casabona.org/events/ features my custom Speaking Events post type.

For example, I created a CPT for my speaking engagements because they all required pretty much the same info. If you go to casabona.org/events/, you will see my "Speaking Events" CPT, which has date, time, title (name of talk), event name, location, description, and for previous talks, a link to presentation resources.

Creating Posts and Pages

Now that you're acquainted with what posts, pages, and CPTs are, it's time to start building! Here are the basics for creating a post in WordPress. We'll be exploring the Posts screen, which is where you will go to add blog posts, news articles, and anything else that gets updated regularly on your site.

1. Click Posts, found in the left sidebar of the WordPress Dashboard.

2. This will bring up the Posts screen, which will look like the one below (except yours won't have a post yet!):

The Posts screen provides access to all your posts. Click the image for a larger view.

Here you have a listing of your posts, along with columns of information about the posts: authors, categories, tags, comments, the date published, and other stats.

Clicking the post title will take you to the post editing interface, while clicking the author or category will take you to the author or category's page, respectively.

You can also bulk edit posts: deleting, unpublishing, or even changing categories and tags on a mass scale. 

3. Ready to add your own post? It's pretty easy. Click the Add New button at the top of the Posts screen. This will take you to the Add New Post screen:

The Add New Post screen allows you to quickly and easily compose a new post, but it also features plenty of other options. Click the image for a larger view.

On the Add/Edit Post page, you'll find several editable areas including post title and an editor for the post body, complete with two modes: Visual, which gives you a WYSIWYG area, and Text, where you can insert HTML and other plain, unformatted text. If supported by the theme, you will also find various post formats, which are described in the next section.

There are also areas for Categories and Tags, with the main difference between the two being that categories organize posts by topic, and tags serve as keywords describing the post. So if the blog post was about WordPress, the category might be "CMS" and tags might be, "WordPress, content, management, system, web, design, development, Web site."  

Post Formats

You'll also see several choices for Format on the right side of your Add New Post screen. These are worth talking about in more depth.

While there are several different types of posts mentioned above, post formats can be described as sub-categories of a post. They are simply displays for posts, similar to how Tumblr allows you to display text, images, videos, and even conversations differently.

You can view all of the post formats for WordPress here: http://codex.wordpress.org/Post_Formats. They include asides (or notes), galleries, images, quotes, statuses, audio, and more.

In order to use them, they must be enabled in your theme or plugin. The Codex recommends that you do it for your own theme in the functions.php file, which we will discuss in the next lecture.

Creating Pages

Here's an exciting thing: adding and editing pages are essentially the same as adding and editing posts. Let me show you how:

1. Click Pages, found in the left sidebar of the WordPress admin area, between Links and Comments.

2. You'll find yourself on a Pages screen that looks suspiciously similar to the Posts screen, which it is. Go ahead and click Add New at the top of the screen, which will take you to the Add New Page screen—which, again, is pretty similar to the Add New Post screen, with one major exception: instead of a Format box on the right side of the screen, we see a Page Attributes box:

With this box, you can do a few things:

 
 
  • The Parent dropdown menu allows you to organize your pages in a specific hierarchy. So if you have a "Menu" page, you could make that page the parent of "Dessert" and "Breakfast" pages, creating a clean navigation hierarchy automatically.

  • Speaking of hierarchy, you can hijack the normal alphabetical ordering system of pages by assigning them specific numbers in the Order field. This will affect the order in which the page links appear on your site's main navigation bar.

  • Finally, you can use the Template dropdown menu to choose a custom template—if those are available in your theme.
 
 

Widgets

Posts and pages form the bulk of WordPress content that visitors see, but you'll also find yourself using widgets to add functionality.

WordPress widgets add content and features to your sidebars. Examples are the default widgets that come with WordPress for post categories, tag clouds, navigation, search, and so on.

WP Biographia is a plugin that adds a very sophisticated About Me-style widget to your sidebar. Like most widgets, it comes with its own admin panel that integrates with WordPress's.

Widgets were originally designed to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. Today, properly "widgetized" WordPress themes can include widgets on the header, footer, and elsewhere in the WordPress design and structure. Many plugins as well will often add their own widgets.

Some WordPress Widgets offer customization and options such as forms to fill out, includes or excludes of data and information, optional images, and other customization features.

Widgets require no code experience or expertise. They can be added, removed, and rearranged in the WordPress admin area from the Appearance > Widgets panel. The order and placement is set by the WordPress theme in the functions.php file. Generally they will be above, below, or to the side of the main content.

To add widgets to your site, go to Appearance > Widgets. There we can drag and drop widgets into the sidebars (or widget areas) that were set up in our theme:

Click the image for a full sized look at the drag and drop widgets area.

If the sidebar you want to modify is collapsed, click the down arrow to the right of the title. From the left area, drag the widget you want to use into the sidebar. Change the settings and click Save.

We'll take a closer look at widgets (and even build our own) in Lecture Six.

Themes and Plugins

Widgets, and the interface used to control them, are one example of how well WordPress separates content from design from core functionality. This ensures that you can continue using the same instance of WordPress and the same content (if you so desire) while changing the look, feel, and features of your Web sites.

But the two biggest ways WordPress achieves this separation are with themes and plugins.

Themes correspond with the design of your WordPress site. They consist of templates, and you can apply different templates to your content to change its look and feel. There are two main ways to get themes: download them, or develop them. In this course, we will be developing our own theme.

The Themes area of the WordPress admin area gives you access to thousands of free WordPress themes.

The wonderful thing about WordPress themes—at least in theory—is that you can swap out one for another without altering the content of the site. Only the look and feel will change.

Why do I say in theory? Well, some themes don't play nice with each other. They come with certain default features that make it difficult to find content that was added in a previous theme, and to a WordPress beginner (or an end user) it can seem like content is lost when a theme is changed. You have to make code customizations or switch back to your previous theme. But this is not how themes should work, only how some of them do work. That's why we're going to build our own!

Plugins, somewhat similarly, are a way of extending the functionality of WordPress without modifying WordPress itself (also known, as I mentioned in the first lecture, as "the core"). So, for example, while WordPress doesn't necessarily support forms, you can download a plugin that will add that support. If you ever decide you no longer want to have forms on your site, simply disable the plugin.

The WordPress Plugin Directory, organized by the most popular plugins.

The most important distinction between themes and plugins is this: themes should deal strictly with look and feel, and plugins should add features, including the addition of custom post types. A lot of times, as I mentioned above, you will find features baked into themes. This is bad practice because functionality is being tied to the design; you will not be able to change the design without removing those features, and possibly content.


Installing a Theme

Installing a theme in WordPress only takes a few clicks. Watch the short video tutorial below to see the process.



User Management

Currently, you're the judge, jury, and executioner of this WordPress blog you've been playing with. This means that you can add posts, change themes, and more—as you've been doing.

But let's say you wanted to bring somebody else in. You want them to write posts, but you don't want them to break the site. Well, WordPress has some really nice functionality built in to manage users and the kind of access they have.

WordPress allows for different levels of contributors, which allows you to make nifty group blogs. (Image credit: allume.com)

First, we have to mention that the user roles break down a little differently between WordPress.com and WordPress.org. Because WordPress.org involves managing an entire site, not just a blog, it offers more extensive and defined user roles.

Since we're going to be moving onto WordPress.org very shortly, we'll focus our look at user roles as they're relevant to WordPress.org. These roles can be a little confusing, so let's break them down one by one:

 
 
  • Super Administrator: The highest possible WordPress.org role, a super administrator has access to all the administration features within a single site and can also access network settings within a multi-site WordPress setup.

    However, a regular administrator has all the same capabilities as a super administrator when you're working with a single site WordPress.org install, which we will be, so the super administrator role isn't really relevant to us.

  • Administrator: An administrator has access to all the administration features within a single site. They can manage plugins, users, posts, and pages—basically anything. Administrators of single site WordPress.org installs can also modify the core (though you should know by now that's not a good idea!).

  • Editor: An editor is a user who can publish and manage posts, including the posts of other users. They can also manage categories, add links or upload files, and moderate comments.

  • Author: An author can publish and manage their own posts, but unlike an editor, an author has no control over the content of others (or comments).

  • Contributor: A slightly but crucially different role than author, a contributor can write and manage their own posts but cannot publish them. In other words, they need an editor to give their posts the go ahead before they go up.

    If you're interested in building sites with guest authors, the contributor role offers great functionality. Administrators can also upgrade the capabilities of contributors without making them full-fledged authors.

  • Subscriber: This role is only available if you have a WordPress.org site. A subscriber is somebody who can log into the dashboard but can only manage their profile. It's useful for when you have a private site that requires registration, or you'd like to give specific users access to private posts or pages.

 
 

You can manage users by clicking Users in the left sidebar in the admin area. As always, check in with the Codex at WordPress.org for more information.

If you'd like to practice adding users and changing roles with your WordPress.com blog before we move onto WordPress.org, WordPress offers a great tutorial on how to do so in their documentation.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Many one click installs set you up with the default username "admin." Sites with this default username become easy targets for hacking, so it's advisable to change the default username if you can.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Keep new users at the "Subscriber" role until you're ready for them to have some form of control in the admin panel.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Having proper permalinks has a major effect on your search engine optimization.

 

 

 

 

 

 

 

 

Moving to WordPress.org
The World Famous Five Minute Install

Now that you're familiar with some of the basics of what WordPress has to offer, it's time to break out of the WordPress.com training wheels and move into a full-fledged WordPress.org site. First, let's see how to install it!

Something WordPress is known for is its world famous five minute install. The idea is to get you up and running as quickly as possible; let me tell you, it lives up to the name. There are two ways to do the WordPress install. The first way is through your hosting providers.

Hosts with One Click Install

Due to WordPress's popularity, many hosts have added "one click" WordPress installs to their hosting panel. In most cases, it's as easy as it sounds: go to your host's admin panel, find where the one click installs are, choose WordPress, fill out the short form and you're done.

The form will ask you which directory to install in, and sometimes the title, admin user name, and password. You should get an email after about 10 minutes with the login information.

Some hosts that offer one click installs, as well as instructions, include:

 
   
 

Even if your host is not listed above, there's a good chance it offers one-click WordPress install. Check with them, or Google "[Your Hosting Company] WordPress Install" and see if instructions are already online.

If you run into any problems installing WordPress, such as the common issue of an out-of-date PHP version, contact your server and they should be able to help you through the kinks.

Manually Installing

If you're feeling adventurous (or your host doesn't support one click, or you're using a localhost like XAMPP or MAMP), you can always do a manual install. It's slightly more complicated, since you need to first create the database where WordPress will live. If you feel comfortable creating a PHP database, click here for the manual installation instructions.

A Walk Through the Settings

Once you've got WordPress installed and working with your Web host, it's time to start combing through the settings.

Once you finish the install, you should be taken right to the WordPress admin area. For future reference, that URL is www.your-domain.com/wp-admin/ (or your-domain.com/wordpress-directory/wp-admin/). The information will also be emailed to you when you finish your install.

Once you're in the admin area, you'll want to click Settings from the left sidebar.

In Settings, you will be able to do everything from setting the Web site's name and timezone to determining the structure of the links. There are a few things I want to point out in each page.

General Settings

Clicking Settings will take you to the General Settings screen. Here you will be able to set the title and tagline (which are both accessible when developing your theme), as well as URLs and email addresses associated with the site. You will also be able to set the timezone and formatting for date and time.

The General Settings page. Click the image to view a full sized version.

Of note is a dropdown called "New User Default Role." If you decide to let users create a username and password for your site, this is the default role they'll be given. I recommend you keep it at "Subscriber" as any other role—like we looked at earlier—gives them some sort of control in the admin panel.  

Writing

Below the General category in the Settings menu on the left sidebar, you'll find Writing. Click it, and you will be taken to the Writing Settings. Here you can set some defaults for your posts, including Category and Format. You will also be able to configure posting via email, though it's not something I'd recommend, for security reasons.

From the Writing Settings page, change your default post category and convert emoticons into graphics.

Reading

Below Writing, of course, is Reading. The Reading Settings are for what the user sees. Most important is the "Front page displays" section. There are two options: your latest posts, which would make your site function more like a blog, or a static page, which allows you to choose a content page to go to whenever a user visits www.your-domain.com. If you want to maintain a blog, you can choose a Posts page as well, though you do not need to.

Under Reading Settings, choose whether you'd like a front page blog, or a static front page.

Permalinks

Permalinks are how you get intuitive, easy to understand links. So instead of:

http://www.your-domain.com/?p=1243

You get:

http://www.your-domain.com/2013/07/this-is-a-post/

On the Permalinks page, you can choose exactly how you want your URLs to look. I generally go with "Month and name" but that's completely up to you.

One thing to be aware of is that descriptive permalinks, which contain keywords, will have a major effect on your SEO (search engine optimiziation). Search engines like Google can look at a URL like casabona.org/10-best-websites-ever/ and know some keywords to associate with the page without even crawling it. A URL like casabona.org/?p=234 does no such service. 

The Permalink Settings screen.

It's worth noting that WordPress allows you to do a lot more with permalinks, but that is a bit more advanced than what we will get into here.

Other Settings

WordPress sites that have large user communities and active comment areas—such as the New York Times—require careful setup in the Discussion Settings area and user moderation.

There are two other settings screens we haven't discussed yet: Discussion Settings and Media Settings.

Discussion Settings are where you will manage how comments are handled. You can do things like turn them off completely, require commenters to be users, set up automatic email to moderate comments, select how approval works, and set up a comment blacklist for certain terms or URLs.

The Media Settings, meanwhile, are where you can set image sizes, location, and organization.

PHP for Wordpress
What is PHP?

PHP stands for "PHP: Hypertext Processor." It is a programming language (like Javascript), as opposed to HTML, a markup language. The main difference is that HTML structures data on a page. PHP allows you to apply logic and perform interactive tasks based on a set of criteria.

PHP is a server-side language, meaning our server (or remote computer) does all of the work, the sends the end result to our browsers. You can imagine the process like a translator — the server translates the PHP into a language our computers can understand. Conversely, HTML, CSS, and Javascript are all client-side languages, meaning our computers, specifically a web browser, does all of the processing. As an example, in PHP, the code would be this:

<?php echo 1 + 1; ?>

However, what we would see in the browser is just 2.

Because of this, you can't develop PHP on any computer. The computer needs to be able to understand PHP, much like you can't speak English to someone unless they also speak English. You can accomplish this one of two ways: purchase hosting and work on a server that understands PHP, or set up a local development environment. I usually recommend both.

TIP: If you're looking for good, affordable hosting, I recommend Web Hosting for Students. It's $25 for the year and works very well.

As far as setting up your own local environment both XAMPP and MAMP are excellent tools.

Since PHP has this ability, it's often used to do heavy duty work on websites — pull information from databases, log-in to secure areas, run calculations and display dynamic data.

PHP Basics

Every PHP Program begins with <?php and ends with ?>. This tells the server to process everything in between these tags.

<?php
	PHP code lines go here
?>

PHP acts as a partner to HTML. It enables HTML to do things it can't do on its own: interactive tasks. PHP code and HTML code can reside together in a file on your website. For example, here is a plain HTML file:

<html>
  <head><title>Hello World Script</title></head>
  <body>
    <p>Hello World</p>
  </body>
</html>

You can write the same script using PHP code by adding PHP tags within your HTML. Here, we will use a basic echo command to write "Hello World":

<html>
  <head><title>Hello World Script</title></head>
  <body>
    	<p><?php echo "Hello World"; ?></p>
  </body>
</html>

WordPress uses this convention heavily to pull information from a database, determine when a user is logged in, process forms, and much much more.

On top of the opening and closing PHP tags, there are a few other important conventions to know:

 
 
  • All PHP files must end in .php

  • Statements (or commands) in PHP end with a semicolon (;).

  • You can add comments (non-functional text) using:

    • //This will be ignored
    • /* This will be ignored and can be multiple lines. */
 
 

One more note before we get into the fun stuff: Dreamweaver has been recommended in other courses, and that will work fine for the WordPress course as well. However, much of the site will not be viewable from within Dreamweaver without going through some level of effort. My recommended workflow is to use Atom and upload your files to your server. This will be covered more in the upcoming lectures.

Variables and Array

Variables are a way to store information in order to reference it later. Variables can be used to store, names, numbers, and other important data. All PHP programs, including WordPress, heavily use variables.

All variables must start with a $, followed by an alpha-numeric character string. Here's an example:

$age = 30;

$age is a place holder for that we have stored the number 30 in. We can then use age as if it's the number 30, printing it, or even doing calculations on in like adding, subtracting, etc. If we decide later we want to change it, we can do that too. Notice the variable is assigned a value using an equal sign (=).

Why use variables?

Variables are easier to keep track of, you can change them on the fly, and most importantly, sometimes you don't know certain information until runtime. WordPress, for example, supports multiple people logging into one system; it's impossible to know someone's name before they log in, so WordPress uses a variable to store a user's name once they log in. You might see something like this:

<?php 
  $username = get_logged_in_user();
  echo "Hello $username!";
?>

Types of Variables

Computers are very specific about how different types of data are represented. Words are represented differently than numbers are, and further, whole numbers are represented differently than decimal numbers.

Luckily PHP handles most of this for us. We do not need to declare what kind of data our variables are most of the time. This makes PHP a weak-typed. It will figure out how we want to use our variables for us.

That said, there are a few different ways variables can be represented:

 
 
  • Integers: These are whole numbers (ex. 0, 1, 45, 128)

  • Floats: These are numbers with decimal points (ex. 1.0, 2.34, 3.16)

  • Characters: These are single letters, numbers, or symbols (ex. 'A', 'b', '1', '@')

    • It's worth noting that 1 and '1' are handled differently by a computer: You can do calculations with 1, but not '1'. Usually PHP is smart enough to know the difference and adjust for us.

    • It's also worth noting that capital letters ('A') are considered different from lower case letters ('a').

  • Strings: These are a collection of characters (ex. 'Hello', 'Joe', 'WordPress')

  • Booleans: A Boolean can have only one of two values: true or false.

  • Arrays: Arrays are collections (or sets) of any of the above variable types.

 
 

While integers, floats, and booleans can be written without the use of quotes (see the example above), strings and characters must be placed in quotes:

<?php
	$name = "Joe";
	$first_letter = 'J';
?>

You'll notice I used both single quotes and double quotes in the example above. There are some nuanced differences to them, but for assignments like these, they can be used interchangeably.

Arrays are a bit different from the rest of our variables. Arrays act as key -> value pairs. Say we wanted a collection of colors. We could store each color in a variable ($color1 = 'red'; $color2 = 'blue';) but that can get cumbersome and hard to manage. Instead, we would use an array:

<?php
	$colors = array( 'red', 'blue', 'green', 'yellow' );
?>

In this example, we have an array of size 4 (there are 4 elements), and we can access any one of these by referencing its key, or index. Indexing starts at 0 for arrays, so an array of size 4 will have indexes 0-3.

<?php
	echo $array[0]; //This will print "red"
	echo $array[3]; //This will print "yellow"
?>

We can also define indexes as strings. Let's look at a slightly more complicated example. Here's an array of information about me:

<?php
	$joe = array('name' => 'Joe Casabona', 'age' => 30,
'profession' => 'Web Developer'); 
?>

Notice that we are replacing the numeric indexes with more friendly names. Now I can reference information like this:

<?php
	echo $joe['name']; //This will print "Joe Casabona"
	echo $joe['age']; //This will print "30"
?>

WordPress makes heavy use of arrays to return information about posts, pages, and just about anything else.

Control Structures

Control Structures are used in PHP to employ logic to our code. They are what do the decision making. The most common of these control structures is if statements, and they can appear one of two ways:

<?php
if ( condition to check ){
	//code to execute if the condition is true}
}

if ( condition to check ):
	//code to execute if the condition is true
endif;
?>

You will see both of these formats in WordPress code. What it says in plain English is this: "If some condition is true, execute this code." Before we look at a more complete example, let's look at what's referred to as "logical operators" — statements that can either be true or false.

We can compare the equality of 2 values with ==. We use "==" to compare, since "=" is reserved for assignments:

 
 
  • 10 == 10 is true

  • 10 == 20 is false

 
 

There are a number of other comparisons we can make as well:

 
 
  • != is "not equal"

    • 10 != 10 is false

    • 10 != 20 is true

  • > is "greater than"

    • 10 > 10 is false

    • 10 > 5 is true

  • < is "less than"

    • 10 < 10 is false

    • 10 < 5 is false

  • >= is "greater than OR equal to"

    • 10 >= 10 is true

    • 10 >= 5 is true

    • 10 >= 20 is false

  • <= is "less than OR equal to"

    • 10 <= 10 is true

    • 10 <= 5 is false

    • 10 <= 20 is true

 
 

We can combine any of these logical operators and check the overall "truthfulness" of a statement:

 
 
  • != is "not equal"

    • (true && true) is true ex. "The sky is blue AND the grass is green"

    • (true && false) is false ex. "The sky is blue AND the grass is pink"

    • (false && false) is false ex. "The sky is green AND the grass is pink"

  • || is "or"

    • (true || true) is true ex. "The sun is hot OR snow is cold"

    • (true || false) is false ex. "The sun is hot OR snow is made of candy"

    • (false || false) is false ex. "The sun is cold OR snow is made of candy"

 
 

Now let's look at a concrete example of an if statement:

<?php 
	if ( 10 >= 5 ) {
		echo "10 is greater than or equal to 5";
	} else {
		echo "10 is not greater than or equal to 5.";
	}
?>

Along with if statements, we can use loops to repeat code or continually check the condition of a statement.

Loops are a fundamental part of WordPress specifically (as we'll see later in the lectures, the important portion of WordPress code is called "the Loop." We will look at two types of loops: While Loops and Foreach Loops.

While loops will continue to execute until the condition is false. Let's say we wanted to print a list of number from 0 to 10:

<?php
	$i = 0;	
while( $i <= 10 ) {
	echo "<p>$i</p>";
	$i = $i + 1;
}
?>

This will print out $i, starting at 0, and each pass through the loop increment $i by 1, until 10 is printed. Once $i is 11, the loop stops executing.

The line $i = $i + 1; is very important here. Without it, the loop will never end.

For each loops are designed specifically for arrays. Let's take our colors example from earlier:

<?php
	foreach( $colors as $color) {
		echo "<p>$color</p>";
	}
?>

This says, "take each color in the array and assign it to the variable $color, one at a time. Then print that color." This loop will end when there are no more elements in the array.

One more note about our conditions. When checking equality, I recommend using "Yoda" conditions; place the variable on the right side of the condition. This will prevent accidental assignments and bugs in your code.

Good:

<?php if( 10 == $i ) { /* do something */ } ?>

Bad:

<?php if( $i == 10 ) { /* do something */ } ?>

They are called Yoda conditions because they read a bit backwards, like Yoda from Star Wars would speak: "If 10, this is."

Functions

Functions are reusable snippets of code that can be called multiple times. You can imagine functions as variables for blocks of code. Functions are formatted in PHP like this:

<?php
	function hello_world() {
		echo "Hello World";
	}
?>

Each function starts with the keyword function, followed by the name of the function, then parenthesis — () — and opening curly brace. The function ends with a closing curly brace.

Functions can do one of two things:

 
 
  • Return a variable

  • Print something out

 
 

We call the above function like this:

<p><?php hello_world(); ?></p>

The result would be:

<p>Hello World</p>

There are several reasons to use functions, but the main one is that if we need to use the code more than once, it would be much easier to put it in a function and call the function. That way if we need to change it, we only need to do so in one place.

If a function were to return a variable, it could be treated as it's own variable or assigned to a separate one. Let's look at a function that returns a boolean:

<?php
	function is_bigger() {
		return 10 >= 5;
	}
?>

This could be used in 2 ways:

<?php
	$bigger = is_bigger();
	if( $bigger ) {
		echo "The function returned true.";
	} else {
		echo "The function returned false.";
	}
?>

or

<?php
	if( is_bigger() ) {
		echo "The function returned true.";
	} else {
		echo "The function returned false.";
	}
?>

Here, the function is treated as a variable. This is a common use in WordPress.

Finally, we can pass variables to functions like so:

<?php
	function is_bigger($a, $b) {
		return $a >= $b;
	}

	$bigger = is_bigger(10, 5); 
?>

Notice that we've added 2 variables to our function, and then when we call the function, send 10 and 5. This gives our functions a lot more flexibility, because now we can send any 2 numbers to compare. You will see a lot of these boolean functions in WordPress; they are often used to track what template we are on, what kind of data is being displayed, and much more.

Functions can do more than just return boolean values. Anything that can be stored in a variable can be returned from a function.

While this isn't a comprehensive look at PHP, this should make reading WordPress code a bit easier. As you move through the rest of the lectures, feel free to refer back here to double-check syntax and figure out exactly what our WordPress code is doing.

Conclusion

That about does it for the introduction to WordPress. In Exercise Two, you will be required to install and mess around with WordPress a bit to get familiar with it. In Lecture Three, we will really dig into nuts and bolts and start developing our own theme!

Learn the advantages of developing a custom WordPress theme.
Explore the directory structure and important files of a WordPress theme.
Learn the sophisticated template hierarchy powering WordPress themes.
Learn how "The Loop," WordPress's core function, powers WordPress content display.
Explore the main and auxiliary WordPress content templates.

Discussion
Share your thoughts on WordPress in the Discussion area.

Exercise
Install, configure, and prepare WordPress for your client's site.