MAP
Welcome
Introduction ...17
In the beginning ...18
Goals of the book...18
Who should read this book ...20
Required skills ...20
Layout conventions ...21
Search & find ...21
Full URLs ...21
Hyperlinks ...21
Chapters, sections, and pages ...21
Code snippets ...21
Footer notes ...22
Side information ...22
Included with the book ...23
2020 + Child Theme ...23
Tao of WordPress + Child Theme ...23
shapeSpace ...23 DIY Theme ...23 General Theme ...23 Simplest Theme ...23 Demo files ...23 Free updates ...23 Reporting errata...24 Useful resources ...24
About the author ...25
Overview
What is a WordPress theme?...27What can themes do? ...29
How themes work ...31
Many types of themes ...34
Free vs. freemium vs. premium ...34
Responsive & mobile themes ...34
Social media focused ...34
Portfolio & photography themes ...34
Starter themes & theme templates ...35
Theme frameworks ...35
Magazine themes ...35
Minimalist themes ...35
E-commerce themes ...35
Bulletin boards & forums ...35
Default WordPress themes ...36
Child themes ...36
Where to find good themes ...36
Free WordPress themes ...37
Premium WordPress themes ...37
Choosing the best theme ...38
Common features ...39
Featured posts ...39 Social media ...39 Advertising ...39 Design options ...39 Contact form...40 Multiple sidebars ...40 Custom menus ...40 Featured images ...40 Widgets ...40 Post formats ...40 Multiple layouts ...40 Child theme ...40
Important things to check ...41
Security ...41 Support ...41 Clean code ...42 Browser compatibility ...42 Responsiveness ...42 Complete styling ...42 Theme options ...42 Awesome design ...43 SEO ...43
Other things to check ...43
Installing & configuring themes ...43
Manual installation ...43
Automatic installation ...43
Configuration ...44
On the front-end ...44
Updating themes ...44
Setting up to work with themes ...45
Server ...45 WordPress ...46 Backups...46 Code Editor ...46 FTP/SFTP software ...48 Web browsers ...48 Devices ...49 On the horizon ...49
Theme Anatomy
Diving in ...51Understanding Page Views ...51
The Template Hierarchy ...53
The simplest theme ...53
Custom template files ...54
Theme template files...56
The simplest theme (revisited) ...57
The most complex theme ...58
Template structure ...58
Behind the scenes ...61
Inside template files ...63
Inside primary templates ...63
Inside secondary templates ...65
Inside tertiary templates ...65
Inside the functions template ...66
Static files ...68
The WordPress Loop ...68
In the Loop, Out of the Loop ...70
Customizing the Loop ...71
Custom loops with query_posts ...73
Custom loops with WP_Query ...74
Custom loops with pre_get_posts ...80
Custom loops with get_posts...83
Custom Loop examples ...86
Controlling the number of posts ...86
Excluding specific categories ...86
Changing the display order ...87
Display a specific Page in any location ...88
Query posts with a specific custom field ...88
Advanced query with custom fields ...89
Custom loops for Custom Post Types ...90
Custom loops for Taxonomies ...91
Paged loops for archive views ...92
Exclude Pages from search results ...93
Display recent posts in the sidebar ...93
Going further... ...93
Template tags ...94
Types of template tags ...96
Conditional template tags ...97
Include tags ...99
Custom template tags ...101
Next steps ...101
Exploring Template Files
Welcome to the tour ...103style.css ...104
CSS ...106
Including style.css ...107
CSS tips and guidelines ...108
index.php ...111
header.php ...113
The DOCTYPE...115
The <html> tag ...115
The document <head> ...115
The <body> ...116
Other header elements ...117
sidebar.php ...119
footer.php ...119
single.php...121
Navigation for paged posts ...121
Display post title and post content ...123
Display the post date ...123
Display the author’s name ...124
Display post categories and tags ...124
Display an “edit” link ...124
Display the comments area ...125
Display post navigation links...125
page.php ...127
comments.php ...127
comment_form ...131
Other tags used in comments.php ...131
functions.php ...132
content.php...133
searchform.php ...135
front-page.php & home.php ...135
archive.php ...137
attachment.php ...138
attachment hierarchy ...139
Custom archive templates ...141
author.php ...141 category.php ...142 date.php ...142 search.php ...143 tag.php ...143 404.php ...144 Custom templates ...144 Archives ...145 Singular ...146
Other important files ...146
Next up ...147
Customizing WordPress Themes
Anything & everything ...149Many ways to customize ...150
Theme settings ...150
Theme Customizer ...150
Plugins & widgets ...150
Shortcodes ...150
Child themes ...150
New theme ...151
Template files ...151
Roll your own ...152
Customize via settings ...152
Using the Theme Customizer ...152
Customize via plugin ...153
Customize via widget ...153
Customize via shortcode ...154
Embed and display video ...155
Embed tweets ...155
Customize via Child theme ...156
Step 1: Create a child theme...156
Step 2: Copy the parent template files ...157
Step 3: Activate the child theme ...158
Customize with a new theme ...158
Customize via theme template files ...159
Example 1: Changing fonts with CSS ...159
Example 2: Create a custom page ...160
Example 3: Customize the footer ...161
Using template tags ...162
Example 1: Display a list of categories ...162
Example 2: Display a list of pages ...163
Example 3: Display a navigation menu ...163
Customizing the Loop ...164
Customize the post content ...165
Customize the post metadata ...166
Customize via functions.php ...167
Customize the <title> element ...168
Enable theme support ...168
Add some shortcodes ...171
Other ways to customize WordPress ...172
Customize via the configuration file ...172
Customize the login screen ...173
Customize the Admin Area ...175
Customize with Post Formats ...176
Customize with Post Types ...177
Customize with Taxonomies ...177
Customizing syndication feeds ...177
Customize the WordPress core ...178
Going further ...178
WordPress Theme Development
Before diving in ...181Build a theme in 4 steps ...182
The Loop is versatile ...183
Diversity of page views ...183
Required tags ...183
Missing tags ...184
View-specific tags ...184
Conditional tags ...184
Adding style ...185
From simple to sophisticated ...186
Step 1: Create the template files ...186
Step 2: Distribute the template code ...186
Step 3: Include the new templates ...188
Layers of development ...189
Build a complete theme in 9 steps ...189
Step 1: Set up ...191
Step 2: Define the theme ...191
Step 3: Define primary templates ...191
Step 4: Customize primary templates ...193
Step 5: Define the content templates ...196
Step 6: Define secondary templates ...201
Step 7: Add some style ...209
Step 8: Add JavaScript ...216
Step 9: Test thoroughly ...219
Going further ...220
Putting it all together ...222
Useful resources ...223
Next steps ...223
Security, Optimization & Testing
It’s all about WordPress ...225Building secure themes ...226
Validating data ...227
Validating numbers ...228
Validating email addresses ...229
Validating file names...230
Validating text input ...231
Validating keys...231
Validating post slugs ...231
Other useful tags for validating data ...232
Sanitizing data ...232
Sanitizing numbers ...233
Sanitizing HTML ...233
Sanitizing XML ...233
Sanitizing attributes ...234
Sanitizing class names ...234
Sanitizing URLs ...234
Sanitizing JavaScript ...235
Sanitizing textareas ...235
Sanitizing text ...235
Sanitizing email addresses ...235
Sanitizing usernames ...236
Sanitizing query strings ...236
Sanitizing database queries ...237
Optimizing theme performance ...240
Optimization techniques ...241
Minimize data size ...241
Minify CSS ...241
Minify HTML ...241
Minify JavaScript ...242
Optimize images and other media ...242
Optimize external resources ...244
Other optimization techniques ...247
Database queries ...247
Custom functions ...247
Remove query strings from static resources ...247
Avoid CSS @import ...248
Query Reduction & Optimization ...248
Optimizing for search engines (SEO) ...249
SEO techniques ...249
Write clean, valid code ...249
Put content first in the markup ...249
Use headings wisely ...250
Use smart navigation links ...250
Include relevant attributes ...250
Testing WordPress themes ...252
Setting up a test environment ...252
Location ...252
WordPress ...252
Recommended plugins ...252
Test data ...253
Displaying & logging errors ...253
Testing code ...254 Testing PHP ...254 Testing HTML ...255 Testing CSS ...255 Testing JavaScript ...255 Testing security ...256 Testing performance ...256 Testing SEO ...256
Premium SEO tools ...257
Testing theme design ...257
Accessibility ...258
Usability ...259
Going further ...259
Front-End Techniques
Ride the wave ...261Design tips ...262 Vertical space ...262 Fonts...262 Colors ...262 Frills ...263 Page layout ...263
Classic fixed-width layout ...265
Fixed-width, right sidebar...265
Fixed-width, left sidebar ...266
Fixed-width layout, two sidebars ...266
Full-width header & footer, fixed-width content ..268
Fluid-width layout...268
Get responsive ...269
Example: responsive sidebar ...269
Rock the header ...272
Step 1: Add some basic markup & style ...272
Step 2: Give it a full-size background image ...273
Step 3: Make it a video background ...273
Add social media buttons ...276
Custom fonts ...278
Custom fonts the "hard" way ...279
Dropdown menus ...281
Step 1: Add the markup ...281
Step 2: Add the CSS ...282
Step 3: Make it responsive ...283
Step 4: Make it a sticky menu ...285
Breadcrumb navigation ...286
Display author information ...288
Sliders! ...290
Base JavaScript ...292
Fixed-width slider ...292
Full-width slider ...294
Video slider ...296
Add lightbox functionality ...298
Step 1: Download the files ...298
Step 2: Add the CSS ...298
Step 3: Add the JavaScript ...298
Step 4: Add the markup ...299
Display a random image ...300
Display a random image using PHP ...300
Display a random image using JavaScript...301
Display a random image using jQuery ...302
Toggle anything with jQuery ...302
Dynamic scroll-to-top link ...303
Advanced Functionality
Anything is possible ...307
Adding support for Theme Features ...308
Custom Post Formats ...308
Post Thumbnails ...310
Custom Backgrounds ...311
Custom Headers ...312
Automatic Feed Links ...314
Navigation Menus ...315
HTML5 (Semantic Markup) ...317
Content Width ...318
Editor Style ...319
Sidebars ...321
Useful tags for theme features ...323
Custom Taxonomies ...324
Step 1: Register the taxonomy ...324
Step 2: Display the taxonomy ...327
Custom Post Types ...329
Step 1: Register the Custom Post Type ...329
Step 2: Display the Custom Post Type ...331
Customizing the Add/Edit Post screen ...333
Enabling Categories, Tags, and Taxonomies ...334
Shortcodes ...335
Display content only to logged-in users ...335
body_class, post_class, & comment_class ...336
Custom taxonomy classes via post_class ...338
Add custom classes ...338
Custom Fields ...339
Example 1: Adding post metadata ...340
Example 2: Updating post metadata ...340
Example 3: Deleting post metadata ...341
Example 4: Displaying post metadata ...341
Custom Meta Boxes ...342
Example: Adding a custom meta box ...343
Adding script and style ...344
Adding JavaScript ...344
Adding CSS ...346
Adding CSS & JavaScript with one function ...347
Using Actions and Filters ...347
Adding action hooks...347
Adding filter hooks ...351
Theme Options ...353
Setting up ...354
Basic Theme Options ...354
File header ...355
Default options ...355
Options menu ...355
Options page ...356
Register settings ...356
Callback function for sections ...357
Callback functions for settings ...358
Callback function for validation ...360
Tabbed Theme Options ...361
Default options ...362
Options page ...362
Register settings ...364
Callback functions for sections ...364
Callback functions for settings ...364
Callback function for validation ...365
Paged Theme Options ...365
Default options ...366
Options menu ...366
Options page ...370
Register settings ...371
Callback functions for sections ...371
Callback functions for settings ...372
Callback function for validation ...372
Using Theme Options ...373
Using multiple theme options ...375
Example: Display Featured Images ...376
Theme Customizer ...377
A basic example ...377
Using theme modification settings ...381
It’s all about control ...382
Going further ...385
Theme plugins and widgets ...386
Wrapping up...387
Sharing & Selling Themes
Hello World! ...389Preparing themes for public release ...390
Development Standards ...390
Theme Guidelines ...391
Testing themes ...391
It’s all about quality ...391
Theme Guidelines Checklist ...392
Appearance ...392
Licensing ...392
Documentation ...392
Required template files ...393
Screenshot ...393 Bundled resources ...393 Validation ...393 Compatibility ...394 Theme namespace ...394 Theme Features ...394 Translation support ...394 Theme classes ...395
Plugin API Hooks ...395
Navigation Menus ...395 Credit links ...395 Untrusted Data ...395 Theme Options ...396 Theme Customizer ...396 Widgets ...396
Script & Style ...396
Functionality ...396
Child Theme ...397
Sanity check ...397
Template Files Checklist ...397
Stylesheet – style.css ...397
Document header – header.php ...398
Sidebar – sidebar.php ...398
Footer – footer.php ...398
Index – index.php ...398
Archive – archive.php ...398
Pages – page.php ...399
Single Post – single.php ...399
Comments – comments.php ...399
Search Results – search.php ...400
RTL stylesheet – rtl.css ...400
Distributing your theme: sharing vs. selling ...400
Sharing free themes ...401
WP Theme Directory ...401
Other venues for distributing free themes ...401
Selling premium themes ...402
You need infrastructure to sell themes ...402
Build it and they may not come after all ...402
Niche themes sell better than general themes ...402
Ongoing maintenance and support ...402
Providing updates forever ...403
Pricing your premium theme ...403
Where to sell your themes ...404
Top theme marketplaces ...404
Selling themes on your own site ...405
E-commerce & shopping carts ...406
Forums & bulletin boards ...408
Promoting your theme...409
Your own network ...410
The WordPress community ...410
Designers and developers ...410
Social media ...410
Search Engine Optimization...410
Advertising ...411
Resources ...411
Build a Starter Theme
Before we begin… ...413About the DIY Theme ...413
Step 1: Set it up ...414
Step 2: Add the markup ...414
header.php ...415
archive.php & index.php ...415
page.php & single.php ...415
sidebar.php ...415
footer.php ...415
comments.php ...415
Step 3: Add the template code ...416
header.php ...416
index.php ...416
not-found.php ...417
page.php ...417
single.php ...419 comments.php ...419 sidebar.php ...422 footer.php ...423 404.php ...423 functions.php ...424
Step 3: CSS, JavaScript, and images ...426
style-editor.css ...426 style.css ...427 custom.js ...429 readme.txt ...429 screenshot.png ...429 Step 4: Testing ...429 Wrapping up...429
2020 Theme Walkthrough
2020 vision ...431About the 2020 theme ...431
2020 overview ...433
Step 1: Media files ...433
Step 2: Template code ...433
Step 3: CSS ...435
Step 4: JavaScript ...437
Steps 5–7 ...438
Functionality & features ...439
style.css ...439 header.php ...442 front-page.php ...447 page-blog.php ...448 index.php ...448 footer.php ...448 inline.php ...449 functions.php ...450 theme-customizer.php ...453 theme-options.php ...454 theme-plugins.php ...455 theme-widgets.php ...455 post-not-found.php ...456
contact-form.php & contact-process.php ...456
post-navigation.php ...456
social-media.php ...457
Make it so… ...457
Appendix
Resources aplenty ...459Getting help with WordPress ...459
General troubleshooting ...460
Read the readme.txt ...460
Disable plugins and themes ...461
Reset the database ...461
Check the server logs ...461
Debugging WordPress ...461
WP_DEBUG ...462
SAVEQUERIES ...463
Show/hide SQL errors ...463
Display all defined constants ...463
Testing in PHP strict mode ...463
Getting the absolute path ...464
Display all PHP information ...465
More debugging tools ...465
Reporting bugs ...465
About this Demo
This is a PDF demo of the book, WordPress Themes In Depth. It contains the entire Table of Contents and the first few pages of each chapter. The complete book contains over 450 pages and is packed with 100% theme-building goodness.
Note that some hyperlinks may be disabled in this demo PDF. In the complete version of the book, however, all hyperlinks are fully enabled and ready to rock.
Introduction
You are about to embark on an in-depth journey through the vast ocean of WordPress theme development. On this voyage you will learn everything needed to customize, build, debug, optimize, secure, share, and even sell your own WordPress themes. You’ll learn how themes work, and how a well-built theme taps WordPress’ wealth of functionality to create a feature-rich interface that delivers the best possible user-experience.
WordPress theme development brings together many aspects of web design, including numerous coding languages, SEO strategy, web security, performance optimization, and everything in between. But as we’ll see, you don’t need to be an expert in every field to build your own awesome themes. Rather, like a chef using prepared ingredients to create delicious meals, you can apply prescribed techniques to build awesome themes.
Whether you are just getting started in web design or have years of experience under your belt, building and customizing your own WordPress themes can be challenging, rewarding, and lucrative. There is much to learn, and with this book as your guide, you are on your way to mastering the craft and creating your own amazing themes. So welcome aboard, may your journey be filled with adventure, discovery, and success.
1
17 Introduction18 In the beginning
18 WordPress themes in depth
19 Goals of the book
20 Who should read this book
20 Required skills
21 Layout conventions
23 Included with the book
24 Reporting errata
24 Useful resources
25 About the author
WordPress Themes In Depth
Page 18
In the beginning
In the beginning, WordPress was new and themes were few. As WordPress grew in popularity, new and exciting themes began to flourish. Designers and developers began pushing the limits of WordPress and sharing their own creative and unique themes with others in the community.
Eventually, WordPress reached critical mass and the premium theme market erupted on the scene. Premium themes boasted awesome features, more functionality, and better customer support. Since around 2007, the ocean of WordPress themes — both free and premium — has grown wide and deep, providing millions of WordPress users with a growing abundance of truly amazing themes. Ever since, WordPress themes have continued to multiply, evolve, and integrate new technologies and design techniques. Today’s themes are diverse, niche-oriented, and loaded with features. Today’s themes are built to be responsive, so they look great regardless of browser or viewing device. And tomorrow’s themes will be even better, with more people building themes and using WordPress than ever before. The theme market remains fierce, but there is an abundance of WordPress users and a wealth of opportunity. With the right mindset and this book as a guide, you’re equipped to customize and build your own awesome themes to use, share, and rock the marketplace.
Goals of the book
The primary goal of this book is to build, customize, and sell your own WordPress themes. To achieve that goal, the book provides the following information:
One of the first default themes, Kubrick was included in many versions of
WordPress from around 2005 to 2010. The above screenshot shows Kubrick version 1.5 working “out of the box” in WordPress 4.0.
ӹ Chapter 1 provides a concise overview of the book.
ӹ Chapters 2–4 explain how themes work and how to get started with WordPress theme development.
ӹ Chapter 5 explains how to customize WordPress themes. ӹ Chapters 6–10 dive deep into theme development, security,
testing, and optimization.
ӹ Chapter 9 provides extensive coverage of advanced techniques, including Theme Features, Custom Fields, Theme Options, and much more.
ӹ Chapter 10 explains everything you need to know to share and sell your own WordPress themes.
ӹ Chapter 11 provides complete steps for building your own lightweight and flexible starter theme.
ӹ Chapter 12 walkthrough of the 2020 theme, which is a premium theme that’s modular, responsive, and full-featured. ӹ The Appendix contains information on getting help,
troubleshooting, debugging, resources, and more.
This book is organized to help you study WordPress themes in depth. In general, the book presents information in cumulative fashion, with each Chapter building on previous material.
As mentioned, theme development brings together many disciplines and coding languages. To help keep things as simple as possible, the book stays focused on theme-building without drifting too far into any one aspect, such as CSS or JavaScript. Throughout the book we will be using CSS, HTML, JavaScript, and PHP, but it’s mostly copy-&-paste followed by explanations. Simplicity and clarity are the key.
Where to begin?
Depending on your current level of experience, you may want to jump in at some specific point in the book. To help with this, here is a quick overview that highlights some of the book’s key areas.
New to WordPress themes? Check out the official guide for new users:
http://codex.wordpress.org/Using_Themes
Theme fundamentals Customizing themes Theme development Build your first theme Build a generalized theme Build a starter theme Premium theme walkthrough Front-end techniques Advanced Techniques Sharing and selling themes Securing themes Optimizing theme Testing themes Chapters 2–4 Chapter 5 Chapter 6
Chapter 3 — Simplest Theme Chapter 6 — General Theme Chapter 11 — DIY Theme Chapter 12 — 2020 Theme Chapter 8 Chapter 9 Chapter 10 Chapter 7 Chapter 7 Chapter 7
Overview
What is a WordPress theme?
According to WordPress.org 1, the latest version of WordPress has been downloaded nearly 30 million times . While not every download develops into a full-fledged website, the ones that do are going to need at least one WordPress theme. That presents a huge amount of potential for theme designers, developers, and marketplaces. So what exactly is a WordPress theme? Technically, a WordPress theme is nothing more than a collection of files that work together to display content to the user. WordPress itself ships with three of its own default themes. These are meant to showcase the diversity and potential of themes, while also enabling the user to customize how their site appears to visitors on the front-end.
Themes enable users to tap into the power of WordPress to display and manage their content exactly as desired. As we’ll see, there are themes for just about every niche and clique imaginable. Users can download themes for blogs, shops, portfolios, magazines, and so much more. Indeed, themes bring together the power of WordPress with the creativity of designers, developers, and savvy users.
Once installed and activated, themes may be customized in numerous ways. Most of the newer, cutting-edge themes ship with loads of options and features, enabling users to dial in the perfect theme without touching a line of code. Other themes, such as starter
1. WordPress download counter: http://wordpress.org/download/counter/
2
27 What is a WordPress theme?
29 What can themes do?
31 How themes work
34 Many types of themes
36 Where to find good themes
38 Choosing the best theme
39 Common features
41 Important things to check
43 Installing & configuring themes
45 Setting up to work with themes
49 On the horizon
WordPress Themes In Depth
Page 22
templates and simple themes, may include no options whatsoever. So in order to customize things, it may be necessary to work directly with template files. Either way, themes provide full control over how content is displayed on the front-end. In terms of customizing site appearance and functionality, the theme is where it all happens. To give you a sense of what’s possible, this chapter showcases some awesome themes from the WordPress Theme Directory. As we’ll see, themes can be very general like the typical default themes, or very specific like a real-estate theme. Themes can be very simple, using as few as two template files, or they can be very complex, requiring hundreds of files. The Twenty Fourteen WordPress theme, for example, is a magazine-style theme consisting of around 70 files.
Further, consider that WordPress-powered sites are dynamic, meaning that content is stored in a database and displayed on the front-end based on the active theme’s template code. In other words, the theme provides a user-interface for accessing database content. Themes also enable customization of the WordPress Admin Area. For example, the 2020 theme includes a set of functions that
customize various aspects of the Admin Area, such as the Login Page, Dashboard, Toolbar, and footer text. Although modifying the Admin Area is best left to plugins, it’s nice to know that themes can do it too.
Twenty Fourteen is a responsive magazine-style theme with a sleek, modern design. (Included with WordPress)
The Wilson theme is one of my favorites. Clean, simple, and responsive. Check it out at the Theme Directory. http://wordpress.org/themes/wilson
Page 23
2. Overview ӹ What can themes do?
WordPress themes have access to all of the functionality provided by WordPress. This means that we can tap into WordPress and use the functions that are needed to display our content as desired. So WordPress provides the functionality, the database stores the content, plugins extend and enhance WordPress, and themes bring it all together with a flexible template system.
Another important thing that themes do is separate the user-interface (UI) from the core WordPress files. This degree of separation enables you to load up on functionality without touching any of the core
files. This means that sites can update the WordPress core without changing anything in the theme, so millions of users to stay current with the latest and greatest. Indeed, themes play an important role on the Web, enabling users to make the most of WordPress.
What can themes do?
As we’ve seen, themes play a key role by bringing together a site’s content, design, and functionality. In doing so, themes tap into WordPress’ vast arsenal of functions, hooks, and tags to generate a UI for interacting with the database. Essentially, themes enable you to harness the power of WordPress to create a unique, highly customized design that suits your site’s purpose, scope, and goals.
Quality is a stylish theme designed for corporate and business sites. Get it at the Theme Directory. http://wordpress.org/themes/quality
Gridster is a responsive portfolio theme for photographers that features a nice grid-based homepage. http://wordpress.org/themes/gridster-lite
Theme Anatomy
Diving in
Now that we’re set up to work with themes and have a general
understanding of what they do and how they work, it’s time to dive in with a in-depth look at theme anatomy. In this chapter, you will learn about the anatomy of a typical WordPress theme. WordPress themes may vary greatly in terms of functionality and features, but the underlying concepts and techniques remain consistent throughout all well-built themes. Understanding core concepts such as Page Views, the Template Hierarchy, and the WP Loop will enable us to customize and build our own awesome themes.
Additionally, we’ll review the basics of using various coding languages such as CSS, HTML, and PHP. Along the way, we’ll look at some examples, apply some techniques, and prepare to go further into WordPress themes in the next chapter.
As you go through this chapter and the remainder of the book, it can be very beneficial to follow along with examples and techniques. If possible, crack open your favorite code editor and browser to get some practical, hands-on experience.
Understanding Page Views
Page Views play an important role in how WordPress themes operate. In WordPress, the Page View refers to the type of web page generated by WordPress. For example, when viewing a single blog post, you’re
3
Theme Anatomy
51 Diving in
51 Understanding Page Views
53 The Template Hierarchy
56 Theme template files
58 Template structure
61 Behind the scenes
63 Inside template files
68 The WordPress Loop
86 Custom Loop examples
94 Template tags
looking at a “single view” or “single-post view”. Likewise, when viewing the archives, you
’
re looking at an “archive view”. It’
s a simple yet important concept that is key to understanding how themes work on the front-end. To get a better idea of how it works, check out the popout box, “WordPress Page Views”, on this page.As seen in the chart above, Page Views are associated with specific URLs. For example, to access a single-post view, we could visit
http://example.com/?p=1 in a browser. If no content is found for the
requested URL, WordPress delivers a 404 (Not Found) page.
Every theme displays something for each type of page view. What that “something” is depends on the requested page and which template files are included in the theme.
For example, if an author-archive view is requested, WordPress checks the theme to see which template files are available to display the page. In general, the process goes like this:
ӹ WordPress first checks for an author-specific template to generate the requested page.
ӹ If an author-specific template is not found, WordPress checks for an archive-specific template.
ӹ Lastly, if no archive-specific template is found, WordPress generates the page using the default template.
This process of using the most specific template to display the requested page is referred to as the Template Hierarchy.
Page View
Home Page (page 1) Home Page (page 2, 3, …) Single Post
Single Page Tag Archive Category Archive Author Archive Date Archive (year) Date Archive (year/month) Date Archive (year/month/day) RSS Feed 404 ( Not Found) Search Results Example URL http://example.com/ http://example.com/?paged=2 http://example.com/?p=1 http://example.com/?page_id=2 http://example.com/?tag=test http://example.com/?cat=1 http://example.com/?author=1 http://example.com/?m=2014 http://example.com/?m=201404 http://example.com/?m=20140407 http://example.com/?feed=rss2 http://example.com/dfgdfgdfgdg http://example.com/?s=searchterm
WordPress Page Views
Here is a quick chart showing the default WP Page Views along with an example URL for each. For all example URLs, remember to change the domain name and paths to match your site.
Note that we’re using the default permalink structure here. If a custom permalink structure is enabled, these default URLs will work, but will be redirected to their new permalink URLs.
Another thing to keep in mind is the example URLs are just that — examples of URLs that, when entered in a browser, will lead to the associated type of page-view. Note that most of these page views are accessible via multiple URLs.
The Template Hierarchy
WordPress’ Template Hierarchy refers to the order in which template files are used to display various types of web pages. Each theme may have a completely different set of template files, but WordPress will always use the Template Hierarchy to determine which files are used to render the requested page. WordPress themes may include as many or as few different template files as needed depending on the design. For example, a complex theme may include a distinct template for each type of Page View, while a minimal theme may use only two or three templates to handle all of them. It’s entirely up to the theme designer to determine which templates are necessary based on the Template Hierarchy.
Before getting into theme template files, let’s take a look at a
simplified overview of Template Hierarchy shown on this page. There we see how the hierarchy applies to different page views. For example, when a single-post view is requested, WordPress first checks for a template file named single.php. If that’s not available, WordPress
generates the page based on index.php, which is one of the two
default template files required for any theme.
✳
The simplest theme
To build the simplest possible theme, we need include only two files:
ӹindex.php
ӹstyle.css 1. Official Documentation: http://codex.wordpress.org/Template_Hierarchy
2. For all of the gory details, check out this infographic: http://bit.ly/1SzhqPc
Theme Template Page View
This simplified look at the hierarchy shows some of the most common-ly seen template files and their associated page views. Also common, but not shown in the chart, are custom template files for posts, pages, and archives. For example, you can create a custom page template for your “About” page by creating a file named page-about.php.
WordPress Template Hierarchy
Here is an overview of the Template Hierarchy 1–2. It includes the mostcommonly used template files and their associated Page Views. For a more complete view of the Template Hierarchy, visit the popout box, “Which template file will wordpress use?” in the previous chapter.
else singular.php singular.php archive.php archive.php archive.php archive.php archive.php if exists home.php front-page.php single.php page.php 404.php tag.php category.php author.php archive.php search.php else index.php index.php index.php index.php index.php index.php index.php index.php index.php index.php
Home Page (posts) Home Page (page) Single Post Single Page 404 ( Not Found) Tag Archive Category Archive Author Archive Date Archive Search Results
Exploring Template Files
Welcome to the tour
In this chapter, we take a complete tour of a “typical” WordPress theme. Good themes may vary wildly in terms of which files are included and which code is used, but they all employ the same general principles and should adhere as closely as possible to the WordPress API. So while the number of contents of various template files may vary, most themes share enough common elements to make possible a “tour” of template files included in the typical theme. As we look at each file, we’ll consider its general purpose, structure, and contents. Along the way, we’ll examine some key techniques for modifying and enhancing default functionality. While staying focused on the code, we’ll also look at how each template file is displayed on the site’s front-end, highlighting cool features and seeing how it all fits together. In this chapter, we’ll be exploring the following template files:
4
Exploring Template Files
103 Welcome to the tour
104 style.css 111 index.php 113 header.php 119 sidebar.php 119 footer.php 121 single.php 127 page.php 127 comments.php 132 functions.php 133 content.php 135 searchform.php
135 front-page.php & home.php 137 archive.php
138 attachment.php
141 Custom archive templates
144 404.php
144 Custom templates
146 Other important files
147 Next up ӹcomments.php ӹfunctions.php ӹcontent.php ӹsearchform.php ӹfront-page.php ӹhome.php ӹarchive.php ӹattachment.php ӹstyle.css ӹindex.php ӹheader.php ӹsidebar.php ӹfooter.php ӹsingle.php ӹpage.php ӹauthor.php ӹcategory.php ӹdate.php ӹsearch.php ӹtag.php ӹ404.php ӹ + misc. files
WordPress Themes In Depth
Page 30
Additionally, this chapter covers custom template files for custom post types, custom taxonomies, and more. Other types of files are discussed briefly near the end of the chapter, where we look at JavaScript, images, and other commonly included files. Think of this chapter as a general walkthrough of the typical WordPress theme. It’s also very complete, so you could follow along and use the information provided in each section to assemble a fully functional theme. Doing so would serve as an excellent exercise for learning how to build your own themes, but the end result would be a rather lean and general looking theme. But no worries — later in the book, we step through the process of building a complete starter theme, and walk through the features of 2020, a premium theme that is fully loaded with tons of functionality and features.
So with that in mind, let’s begin the tour!
style.css
style.css is the theme’s main stylesheet. It is required for a theme
to be recognized by WordPress, and it must always be included in the theme’s root directory. Further, style.css must always include a
proper file header 1. The style.css header includes the theme’s name, description, author, license, and other essential information.
A typical style.css header looks like this:
/*
Theme Name: General Theme
Theme URI: http://example.com/general-theme/ Author: Theme Designer
Author URI: http://example.com/
Description: A hypothethetical, generalized typical theme Version: 1.0
License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: black, white, light, dark, two-columns
Text Domain: generaltheme Domain Path: /languages */
This file header is included as an inline comment. When writing CSS, inline comments give designers a place to include non-CSS content in the stylesheet. So, for example:
/* this is a single-line inline comment */
And likewise:
/*
this is an inline comment that spans multiple lines */
If you look through the style.css file of WordPress’ Twenty Fourteen
theme, you will find inline comments used to organize the code and convey useful bits of information.
Page 31
4. Exploring Template Files ӹ style.css
In general, the style.css header should include as much information
as possible, however, technically, only the Theme Name is required in order for WordPress to recognize and utilize the theme. Other header information is optional, but should be included if the theme is to be made available to the public. We’ll learn more about this in Chapter 10, where we learn how to prepare our themes for public use. For the sake of completeness, here is a quick explanation of each line in the
style.css header, along with any relevant details.
ӹ Theme Name – the name of the theme, can be anything, but must be unique among other installed themes
ӹ Theme URI – the online location of the theme’s homepage ӹ Author – the name of the author, should be the author name,
or the author’s username if registered at wordpress.org ӹ Author URI – the online location of the author’s homepage ӹ Description – a clear, succinct description of the theme ӹ Version – the version number of the theme
ӹ License – the name/summary/link of the theme license ӹ License URI – the online location of the license
ӹ Tags – tags used to describe the theme, also used to help users find new themes when searching the WP Theme Directory1
ӹ Text Domain – the theme’s text domain, used in localization and theme translation2
ӹ Domain Path – the path to the theme’s localization files, relative to the themes directory3
As you get started in theme development, don’t worry too much about including all of these details. Include as much information as possible to get going, and then revisit as needed to supply
additional details. For example, it’s probably not necessary to include international language support in your first theme, so it’s fine to exclude the Text Domain and Domain Path information. Then, once you get to the point where you want to share or sell your own themes, read through Chapter 10 to learn how to hook everything up and provide a complete style.css header.
One more note about the style.css header, it’s fine to include
additional information as well. For example, in the Twenty Fourteen WordPress theme, the style.css header includes the following
additional information:
/* ...
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.
*/
That’s just free-floating information included at the bottom of the style header; it could have been 30 paragraphs of text and it would still be fine. WordPress only cares about the information associated with the keywords defined in the previous list.
1. This is why tags are important: http://wordpress.org/themes/tag-filter/
2. See Translation Support in Chapter 10, and learn more at the Codex: http://codex.wordpress.org/I18n_for_WordPress_Developers
Customizing WordPress Themes
Anything & everything
Perhaps the greatest thing about WordPress is its flexibility. Regardless of your skill level, there are a million ways to customize WordPress to create the perfect site. This chapter is for anyone who wants to customize their theme. It explains all the main ways of doing so, provides a wealth of examples, and broadens our perspective of how the theme fits into the grand scheme of things.
With WordPress, not only is it possible to customize virtually any aspect of your site, there are myriad ways of doing so. For example, just looking at the sidebar, we can customize using widgets, the style template, the sidebar template, or a child theme. It’s also possible to make changes via the functions template or a plugin, depending on which strategy makes the most sense.
As you read through this chapter, it’s a good idea to follow along with one of the demo themes or one of the default WordPress themes. Don’t hesitate to experiment with different techniques and ideas — it’s impossible to permanently “break” anything if you have current backups of your database and files 1.
One more note before diving in, some of the techniques in this chapter are fine to apply to a live site. For example, it’s fine to customize widgets on a live site. Other techniques should be implemented while the site is not accessible to the public 2.
1. See Setting up to work with themes in Chapter 2. 2. See Local vs. live in Chapter 2.
5
Customizing WordPress Themes
149 Anything & everything150 Many ways to customize
152 Customize via settings
152 Using the Theme Customizer
153 Customize via plugin
153 Customize via widget
154 Customize via shortcode
156 Customize via Child theme
158 Customize with a new theme
159 Customize via theme template files
162 Using template tags
164 Customizing the Loop
167 Customize via functions.php
172 Other ways to customize WordPress
WordPress Themes In Depth
Page 34
Many ways to customize
There a million and one ways to customize WordPress. But you don’t want to just jump in and start changing things without a plan. First, make sure you understand what you are doing. Whether it’s a widget, plugin, or custom function, make sure you’re paying attention, especially when making changes on a live site. It’s fine if you don’t understand the precise mechanism behind every snippet of code, so long as you’re getting your information from a reliable source.
A good strategy for customizing themes is to keep it simple and begin with the least invasive, most applicable method. Whenever possible, use WordPress’ native settings and features to customize your site. When that’s not possible, see if there is a widget or plugin that will do the job. When none of these methods suffice, you can customize the theme template, either directly or via Child Theme.
To put things into perspective, here is an overview of the customization methods that are covered in this chapter.
✳
Theme settings
Most themes these days include a Theme Options screen in the Admin Area. If so, this should be the first stop for customizing your theme. As much as possible, any customization should be accomplished through the Theme Options screen.
✳
Theme Customizer
The Theme Customizer makes it simple to customize various as-pects of your theme. Themes vary, however, in terms of how well the Customizer is supported. Many themes provide options for changing things like titles, taglines, and colors, but other theme features like custom backgrounds and custom headers require theme support. If in doubt, check the theme’s documentation.
✳
Plugins & widgets
As we’ll see in the next chapter, plugins are an excellent way to add, change, or remove existing WordPress functionality. For example, if a theme lacks a built-in contact form, simply install one of the many contact-form plugins and move on with your life.
✳
Shortcodes
As we’ve seen, shortcodes make it easy to include custom snippets with your posts and pages. If your theme includes shortcodes, they may enable the required customization. New shortcodes may be added directly via functions.php, or from a theme or plugin.
✳
Child themes
The next best way to make changes to your theme is using a child theme. As discussed in the previous section, child themes enable you to overwrite any part of the theme with custom functionality. Customizing via child theme is smart because the parent theme’s template files remain unmodified.
Page 35
5. Customizing WordPress Themes ӹ Many ways to customize
✳
New theme
Another option for changing your site’s design is to find a new theme. There are so many great themes available, it’s generally easy to find something that fits the bill. Visit Chapter 2 for more information about different types of themes and how to find good themes.
✳
Template files
It’s also possible to make changes to the theme itself. By editing a theme’s template files, you’re able to customize literally anything you wish. So if there’s something that needs customizing, and it’s not possible to do so using any of the methods above, editing the template files should get you there.
Admin Area & default WordPress settings Install & configure themes/plugins
Configure theme options/ widgets
Customize theme tem-plate files
Edit some WordPress core files.. Easiest. Easy to Advanced (usually easy) Easy. Medium/Advanced (varies with theme) Never do this. Basic functionality such as enabling/disabling comments, the number of posts to
display, enabling/disabling registration, setting up permalinks, etc.
Everything under the sun, but some niches/functionality are hit or miss. Plus, some plugins may require advanced configuration.
Colors, font-sizes, positioning of sidebars, header images, background images, menus, widgets, colors, fonts, and potentially much more, depending on the theme. Page structure (HTML), appearance (CSS), behavior (JavaScript), and dynamic func-tionality (PHP). Essentially, anything is possible via template customization. Literally any aspect of WordPress. As a rule, you should never change any core files on a production site. There is always a better way.
Method Things that can be customized Difficulty
WordPress Theme Development
Before diving in
To put things into perspective, WordPress theme development is just a small part of the much larger field of dynamic web development. Anything that can be built with regular coding languages like PHP, HTML, JavaScript, and CSS, also can be built with WordPress. Of course, the more you know about these languages the easier it’s going to be to learn how to build WordPress themes, but there is no need to be an expert in everything. In this chapter, you will see how easy it is to get started with WordPress theme development, and learn the principles and methodology needed to go further.
Before diving in, it’s important to know exactly where we’re at and where we’re going. At this point in the book, we have a solid understanding of WordPress theme structure and how template files are used to display content on the front-end. We’re now ready to apply this information and build some amazing themes.
To get there, we’ll need to stay focused on the theme itself, without veering too far into any particular aspect of web design. It would be easy to get sidetracked on, say, the graphic design aspect of web design. Or spend an entire chapter on the latest UX/UI wizadry. Or go chapters deep into mobile design and advanced JavaScript techniques. Instead, we’re going to keep things simple and focus on building awesome themes.
As we go, keep in mind that there are many ways to go about building WordPress themes — there is no “one right way” to do it. Building
6
WordPress Theme Development
181 Before diving in182 Build a theme in 4 steps
186 From simple to sophisticated
189 Layers of development
189 Build a complete theme in 9 steps 222 Putting it all together
223 Useful resources 223 Next steps
WordPress Themes In Depth
Page 38
themes is like playing music. Yes you can just play the notes, but the results will be plain and ordinary. To really rock a WordPress theme, you need to find your own rhythm, and that requires understanding and lots and lots of practice. This book provides the understanding, and this chapter provides the fundamentals so you can dive in and start practicing.
Build a theme in 4 steps
Before doing anything, let’s see how easy it is to build a simple WordPress theme in four simple steps:
Step 1
In the WordPress /themes/ directory, create a folder named /simplest-theme/
Step 2
In the new directory, create two new (empty) files, style.css
and index.php
Step 3
Open style.css and add the following code:
/* Theme Name: Simplest Theme */
Step 4
Open index.php and add the code provided in the next
column.
Congratulations, you just built a WordPress theme.
<!DOCTYPE html> <html>
<head>
<title><?php bloginfo('name'); ?><?php wp_title(); ?></title> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head> <body> <header>
<h1><a href="<?php echo home_url('/'); ?>"> <?php bloginfo('name'); ?></a> </h1> <p><?php bloginfo('description'); ?></p> </header> <article> <?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?> <div class="post">
<h2><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a> </h2> <?php the_content(); ?> </div> <?php endwhile; ?> <div class="post-nav"> <?php posts_nav_link(); ?> </div> <?php endif; ?> </article> <footer>
<p>© <?php echo date('Y'); bloginfo('name'); ?></p> </footer>
</body> </html>
Page 39
6. WordPress Theme Development ӹ Build a theme in 4 steps
Yes, it is a simple theme, but it is suitable for displaying content for every type of page view (e.g., single posts, archives, etc.).
If you followed along with the four steps, go ahead and install and activate the “Simplest Theme”. Then surf around the front-end of your site and check out the various page views to see how things look with a theme that weighs under 12 KB. For example, if your site is located at http://example.com/, try visiting the following URLs:
As you can see, a mere 38 lines of code gets you a fully functional theme that displays content for every type of page view. Sure, without any CSS, the markup looks plain and boring, but the Simplest Theme illustrates some key concepts:
✳
The Loop is versatile
One default loop in the index.php is “smart” enough to display the
correct content for each type of page view. It doesn’t matter how many template files a theme might have — one or many — the Loop always knows exactly which posts to display.
✳
Diversity of page views
Using a simple template file (i.e., index.php) to display all page views
means that all page views are going to look virtually identical. As discussed in depth in Chapter 3, the Template Hierarchy enables us to customize the appearance of different page views, so search results can look like search results, Pages can look like Pages, and so forth.
✳
Required tags
Are there any required tags for WordPress themes? The short answer is “no”, but it also depends on how the theme will be used. For personal themes that nobody else will use, you can knock yourself out and use as many or as few template tags as desired. But if you’re planning on distributing your theme for others to use, then the answer is “yes”, and there are a number of template tags that should be included 1–2.
1. See Theme Guidelines Checklist in Chapter 10.
2. See also: https://developer.wordpress.org/themes/getting-started/your-first-theme/
URL http://example.com/?p=1 http://example.com/?page_id=2 http://example.com/?paged=2 http://example.com/?cat=1 http://example.com/?author=1 http://example.com/?m=2014 http://example.com/?m=201401 http://example.com/?m=20140101 http://example.com/?s=hello http://example.com/404page Page View Single Post Single Page
Paged view of Home Page Category Archive Author Archive Year Archive Month Archive Day Archive Search Results 404 Not Found
Security, Optimization & Testing
It’s all about WordPress
The good news is that securing, optimizing, and testing themes is much easier than doing the same for an entire installation of WordPress. The not-so-good news is that a lot of work may be required to secure and optimize things at the theme level. Of course, the amount of work required depends on the theme. Themes that use the WP API whenever possible tend to require less work than themes that go it alone with their own custom code. This is why, throughout the book, we stick close to the WP API in every step. Whenever possible, we let WordPress do the heavy lifting and keep our template code as clean as possible. This way, we are baking security, performance, and SEO right into the theme, rather than tacking it on at the end. In this chapter, we dive into theme security and optimization, and learn how to test many different aspects of WordPress themes.
In general, security, performance, and SEO work together to determine the overall quality and success of a website. Search engines such as Google determine site quality by measuring signals of quality like performance, relevancy, reputation, and many other factors 1–2. In this chapter, you will learn how to optimize for these factors at the theme level, where good organization and clean code serve as the foundation.
1. See Google PageSpeed: https://developers.google.com/speed/pagespeed/
2. See Yahoo! YSlow: http://yslow.org/user-guide/
7
Security, Optimization & Testing
225 It's all about WordPress226 Building secure themes 227 Validating data
232 Sanitizing data
240 Optimizing theme performance
241 Optimization techniques
247 Other optimization techniques 249 Optimizing for search engines (SEO) 249 SEO techniques
252 Testing WordPress themes 252 Setting up a test environment 254 Testing code
256 Testing security 256 Testing performance 256 Testing SEO
257 Testing theme design 258 Accessibility
259 Usability 259 Going further
WordPress Themes In Depth
Page 42
After completing this chapter, you will have a better understanding of how it’s really “all about WordPress”, and how we can work with the software to create themes that are secure, tested, and well-optimized. Doing so enables us to build high-quality themes that are appreciated by both human visitors and search engines.
Building secure themes
On the Web, security is “mission critical” for success. Just as a chain is only as strong as its weakest link, so too is WordPress only secure as its weakest plugin or theme. For example, if you are running a default installation of WordPress with only the default plugins and themes, your site would be as secure as WordPress itself, which is considered very secure. Each plugin that you add, however, may or may not be as secure as WordPress. Likewise with your theme, if it is less secure than WordPress, then the entire site is only as secure as the theme. Fortunately, securing a WordPress theme is generally much less work than securing an entire website. Even better, themes built with the WP API generally are secure out of the box, with no further security measures required. For example, when using high-level functions like get_bloginfo() and wp_list_categories(), database queries are
sanitized by WordPress’ internal functionality, so there’s no need to take extra steps to sanitize the data.
As you develop a theme, there are a few things to keep in mind to help ensure an optimal level of security:
ӹ Trust WordPress – use the WP API whenever possible. ӹ Trust nothing else – all data entered by the user or retrieved
from the database should be considered unsafe. ӹ Validate all input data, sanitize all output data.
To put these points in perspective, let’s return for a moment to the general theme built in the previous chapter. If you revisit each theme template, you will see that they are built with the WP API. All of the data is output via WP’s own template tags, and there are no weird custom functions that might introduce any security vulnerabilities. Such themes may be considered to be as secure as WordPress itself. Now let’s say that we wanted to add a front-end form that enables visitors to submit their own posts. Adding such a feature would introduce a new vulnerability that may be exploited if not properly secured. Thus, in order to keep things secure, we apply the rule, “validate all input data, sanitize all output data”. On the front-end, this means that we want to validate all data that the user enters into the form. This can be done either client-side (using JavaScript) or server-side (using PHP). As we’ll see later in this chapter, WordPress provides plenty of template tags to use when validating user input. Contrary to what one might expect, after the validated data is entered into the database, it still must be treated as unsafe. This is because of the dynamic way in which database content is used. For example, it is fine for post titles to contain single or double quotes when displayed inside of heading tags (e.g., <h1>, <h2>), but not when displayed inside
Page 43
7. Security, Optimization & Testing ӹ Validating data
<a href="<?php the_permalink(); ?>" title="Read the full article: <?php the_title(); ?>"><?php the_title(); ?></a>
When used in the Loop, this code will display a link that uses
the_title() for both the link text and title attribute. If none of the
post titles include any quotes, this code is fine. If, however, some of the post titles include quotes, using the_title() for the value of the
title attribute can lead to broken markup. For example, if our post title was something like this:
This post title uses "double quotes".
The double quotes would “break” the markup used to display the title. Viewing the source code on the front-end, this would be displayed as:
<a href="http://example.com/this-post-uses-double-quotes/" title="This post title uses "double quotes"">This post title uses "double quotes"</a>
Notice the problem with this code? The double quotes included in the value of the title attribute can cause browsers to misinterpret the
syntax and break things when displaying the web page. Thus, the title data may be fine in one context (the link text), but not in others (the
title attribute).
Likewise with other data — it may have been properly validated for one purpose, but may be used for other things as well. This is why it’s necessary to sanitize all output data, even if it’s validated before it gets to the database.
So it all depends on context. Without knowing the context in which the data was collected, there is no way of knowing whether or not it is safe to use. Incidentally, WordPress provides its own tag for displaying the title attribute:
<?php the_title_attribute(); ?>
This tag sanitizes the output data to make it safe for use in attributes. In this case, the sanitization includes converting quotes to their HTML equivalents, for example:
This post title uses “double quotes”
With the quotes properly converted to their respective entities, the title output by the_title_attribute() is safe for use in attributes.
This example illustrates why it is important to always validate input data and sanitize output data. To make developers’ lives easier, WordPress provides a complete set of template tags that may be used to validate and sanitize any data that’s required.
Validating data
Validating input and sanitizing output are important concepts, so let’s take some time to study each in depth, and then look at some useful WordPress functions that make our development lives easier. Whenever accepting input data, it is necessary to validate it. Data validation is all about making sure that the data is exactly what it is
WordPress Themes In Depth
Page 44
Front-End Techniques
Ride the wave
The field of web development evolves rapidly, with new tools, techniques and technologies constantly opening new doors and new ways of building websites. Over the years, web design and development have branched into numerous disciplines.
If you’re looking for work these days, you’ll need to know whether you are a UI Designer, UX Designer, Frontend Developer, Interaction Designer, SEO Specialist, Design Coordinator, or Full-Stack
Developer. Within each of these areas, the methods and tools also are diversifying and evolving rapidly. It’s almost a full-time job just keeping up with everything.
To put things in perspective, when I first started in web development over 10 years ago, we used CSS. Now, in addition to CSS, we have LESS, SASS, OOCSS, SMACCS, BEM, and so on 1–4. The list of acronyms grows every year, along with the amount of awesome stuff that you can do with all of the new technology. The good news is that plain old CSS still works great, but you are encouraged to branch out and explore as many tools as possible; each brings something new to the table and will improve your own understanding and experience. In this chapter, we stay focused on theme building and explore some useful techniques for customizing the front end of your theme. These
1. BEM approach to front-end development: http://bem.info/
2. SMACCS (Scalable and Modular Architecture for CSS): http://smacss.com/
3. Dive in (top results for OOCSS): https://www.google.com/?s=oocss#q=oocss
4. Job Titles in the Web Industry: http://bit.ly/1mHyV18
8
Front-End Techniques
261 Ride the wave
262 Design tips 263 Page layout 269 Get responsive 272 Rock the header
276 Add social media buttons 278 Custom fonts
281 Dropdown menus
286 Breadcrumb navigation 288 Display author information 290 Sliders!
298 Add lightbox functionality 300 Display a random image 302 Toggle anything with jQuery 303 Dynamic scroll-to-top link 305 Up next...
WordPress Themes In Depth
Page 46
techniques draw upon what we’ve learned so far in the book, and will help to get you started in the dynamic field of front-end development. Note that all of the examples for this chapters are included with the book as demo files, so you can follow along and see how each technique works. So surf’s up, let’s hit some waves!
Design tips
If you’re new to front-end development, here are some useful things to keep in mind as you learn the ropes. These are just general tips for those who may be unfamiliar with some of the basics.
✳
Vertical space
Web pages are not like pieces of paper — there is no fixed length that requires designers to cram everything to fit on the page. This gives designers and developers the freedom to use plenty of vertical space when writing their CSS. Here are some good ways to ensure that things don’t look all mashed together:
ӹ Define a healthy line-height for text
ӹ Apply ample vertical margins to block-level elements
Making sure that page items have plenty of room to breathe can make a lot of difference in the overall look and feel of a theme.
✳
Fonts
Thanks to the ability to define custom fonts in our stylesheets, it’s easy to get carried away and use too many. When selecting fonts for your design, a good rule of thumb is to keep it simple. Using a minimal number of fonts keeps your design looking clean and organized, and also improves the load time of your pages.
Further, use fonts that are easy to read. When defining font styles, use sufficiently large font-sizes with ample line-height.
✳
Colors
Unless the theme design calls for it, it’s best not to go crazy with colors. When getting into CSS, it’s easy to get carried away and define a different color for everything, but doing so generally results in
Inspect your code
Just a reminder that cool browsers like Chrome and Firefox include built-in code inspectors that make it easy to check your source code while viewing it in the browser.
In Chrome, you can right-click on any element in a web page, and then select “Inspect Element”. That will bring up the code inspector, which you should get to know — it is a huge timesaver.
In Firefox, you can right-click on any element and select either "Inspect Element" or "Inspect Element with Firebug" to use Firefox’s built-in code inspector or Firebug extension, respectively.