Mastering The Fundamentals Of WordPress Themes

Transcription

Mastering theFundamentals ofWordPress ThemesHow Themes Work, and How to MakeThem Work For YouBrought to you bySponsored by

IntroductionContentsIntroduction . 2The Four Languages You Must Know to Understand WordPress Themes . 3The Three Core Concepts of WordPress Themes . 8Demystifying “The Loop” in WordPress . 12Understanding the WordPress Template Hierarchy . 16Make Your Themes Better By Getting to Know get template part(). 19WordPress Post Template Tags: What They Are, How You Use Them, and Why You Care . 23How to Link to Your WordPress Theme Resources . 27Four Things a WordPress Theme Shouldn’t Do . 30Dealing with Theme Creep . 34Always Use a Child Theme! . 36Summary . 39WP ShoutPage 1 of 39

IntroductionIntroductionWordPress is the most powerful website builder and content management system in the world.There, we said it.Much of that power comes from WordPress’s thorough and ingenious use of themes, which cangive users a huge head start toward creating exactly the site look-and-feel they’re after.But there’s more to themes than choosing them, setting them up, and selecting theme options.The theme paradigm offers a lot of power and flexibility to people with a bit of technical savvy:WordPress developers and empowered WordPress site owners.Mastering the Fundamentals of WordPress Themes aims to help you become one of them. We’ll belifting the hood on WordPress themes—so you can start to see how they work, how they fittogether, and how you can build and modify them to meet your own needs.We’ll be covering the following: Core principles: what WordPress themes are, what they do, and how they work in theirfundamentals. Key features: elements like post template tags and the get template part() functionthat will hugely improve and streamline your work with themes. Best practices: basic do’s and don’t’s that will help you make the right decision forthemes you build or modify.Let’s get started!WP ShoutPage 2 of 39

The Four Languages You Must Know to Understand WordPress ThemesThe Four Languages You MustKnow to Understand WordPressThemesTo be able to make WordPress themes, you’ll need to main areas of knowledge: languages andconcepts.The first, and our topic in this chapter, is more general: you must understand the basic“languages” involved in making a theme. These are:1. HTML2. CSS3. PHP4. (Somewhat optional) JavaScriptIf you don’t have a basic understanding of what each of those are and how they work, you’llspend a lot of time spinning your wheels. So let’s dive into them.HTML, Huh? I’ve Heard of That!HTML is the one universal part of the “world wide web”.Though it has variants and versions, every page you seeon the internet with content inside of it is marked upwith HTML. There are no exceptions to this. Some pageswill have essentially no content inside the HTML, whichcould only be there to load up some JavaScript, but withscant exceptions if you’re seeing it in a web browserthere are some HTML tags on it. And if there aren’tHTML tags on it, they’re interpolated by the browser soit can make sense of the unmarked up content.HTML isn’t really a “programming” language, it’s a “markup” language—as you probably know, itstands for HyperText Markup Language. What this means is that it’s essentially just a big textWP ShoutPage 3 of 39

The Four Languages You Must Know to Understand WordPress Themesdocument, but with “markup” baked into it to explain the specific meaning of the various bits oftext. Here’s a bit of HTML. !DOCTYPE html html head meta charset "UTF-8" / title Page Title /title /head body h1 Title of Page /h1 p class "lorem" Lorem ipsum dolor sit amet /p /body /html This is a full, but very small, HTML page. The big thing to know is that most elements arecontained between two different tags, which are themselves bound by less-than and greaterthan signs. Some elements are self-closing ( meta charset / in this example), andelements can be given attributes, like the class of lorem defined on the p , or paragraph,element.CSS: Making HTML Look GoodCSS, which stands for Cascading Style Sheets, is the waythat (almost all modern) webpages are given a specificappearance. In CSS you’ll style either HTML elements,like an h1 or a class, like the lorem we called outearlier. In either case the syntax is pretty uniform, andlooks like this:.lorem {font-family: 'Libre Baskerville', sans-serif;}The big thing to notice here is that we’re declaring rules, plus the HTML element (orelements) that the set of rules affects. In this case, we first decide that the rule applies only tothose elements given the lorem class. Then, inside the curly braces, we declare the property—font-family, meaning which font to use—followed by a colon. Then we declare the value ofWP ShoutPage 4 of 39

The Four Languages You Must Know to Understand WordPress Themesthat property: “Libre Baskerville” or, failing that, the default sans-serif fallback font. We followthe whole declaration by a semicolon. New lines after the semicolons are common but notnecessary.The hard part about CSS is to know which properties to use to give your page the appearanceyou want. Whole books are written about that topic, so we’ll move on.PHP: The Engine of WordPressPHP is what runs WordPress on your web server.Whether your site is on WordPress.com or is a selfhosted WordPress.org site, it’s using PHP on theserver to build your pages and put them together.Therefore, PHP is (arguably) the most importantlanguage for truly understanding WordPress. Allthe core concepts we’ll be talking about with respectto WordPress themes take place within the context ofPHP running on the web server.PHP was initially built with the intent of allowing more intelligent creation of HTML pages. It’s ahypertext preprocessor, meaning a language that generates or modifies HTML directly on theserver, before it gets sent to your browser. This is the “HP” in “PHP.” (Believe it or not, the first“P” stands for “PHP” itself, making the full acronym PHP: Hypertext Preprocessor. This is whatnerds call a “recursive acronym,” on those rare occasions when anyone will talk to them.)So when a visitor requests a page on your site, PHP creates the page right on your web server(the place where your site is hosted). Once PHP has done its work, the server will send thegenerated HTML markup to the visitor’s browser, which then displays it.For WordPress themes, the basic logic and structures of PHP are what’s really important. Here’sa snippet, which we’ll then explain.WP ShoutPage 5 of 39

The Four Languages You Must Know to Understand WordPress Themes ?php variable 4; math variable 1;if ( math variable) {echo "Yay. Math yielded math! ";echo 'Variable was '. variable.'.';}? p I'm an HTML paragraph. Hi! /p ?php if (true) : ? p I'm HTML that will render. /p ?php endif; ? ?php if (false) : ? p I'm HTML that won't render. /p ?php endif; ? There are a few important things to know about this. First, anything that’s not within PHP tags( ?php and ? ) is just going to come out to the visitor as ordinary HTML when that file isreceived from the server.Also, variables in PHP start with a dollar sign, and you do math with them just about like you doin algebra class.Within a block of PHP, you use the echo commend to render things out the final page.The final big thing that our example points out is that HTML which is surrounded by PHP logic iscontrolled by it—this is why the HTML inside the first PHP conditional will show up on the page,but the second won’t.There’s loads more to understand about PHP, but this is a start.WP ShoutPage 6 of 39

The Four Languages You Must Know to Understand WordPress ThemesJavaScript: Let’s Program Web BrowsersJavaScript (no acronym, thankfully) is a flexibleprogramming language whose main use in aWordPress context is to control the behavior ofHTML pages after they’ve hit the visitor’s webbrowser. So if you click a button somewhere on a site,and the background color of the site fades from red toblue, that’s most likely (a weird use of) JavaScript.JavaScript has seen a big resurgence in the last halfdecade, primarily because client-side scripting(another way of saying “code that executes in the browser and can interact with the user in realtime”) can be so valuable: it allows for much quicker interactions and a sense that the page isreally working for you, the user. This is the purpose for which JavaScript was invented, and stillits most common use case—though people are starting to use it everywhere else, too.A WordPress theme can work perfectly and run very well without using JavaScript at all; but, likemuch of the web, JavaScript is seeing more and more use inside both WordPress themes andthe core of WordPress itself. However, we’ve already gone on quite long about the otherlanguages, so I’ll skip the examples of JavaScript entirely for now.Now You KnowObviously we’ve barely scratched the surface of how these four languages work, and how youcan use them effectively in WordPress themes. But I hope we’ve armed with you just enoughknowledge to feel prepared to change the colors on your site with CSS, change your headermarkup with HTML, or start to modify the logic of your theme templates with PHP. Just knowingthese four languages and how they differ is a great place to begin to understand and work withWordPress themes.WP ShoutPage 7 of 39

The Three Core Concepts of WordPress ThemesThe Three Core Concepts ofWordPress ThemesTo really comprehend what WordPress themes are doing, you’ll need to understand threeprimary core concepts:1. The template hierarchy2. “The Loop”3. The basic dynamics of hooksIf you understand these three things, you’ll then be able to manage and quickly learn thespecific syntax and necessary functions for making a WordPress theme.First, though, we’re going to start with a metaphor that will clarify and contextualize the wholediscussion.WordPress is a Factory for Processing Posts into WebpagesI think the easiest way to understand thesethree key concepts is by analogy. So I cameup with one I like pretty well: WordPress is afactory that makes webpages. Morespecifically, it processes one or moreWordPress posts stored in your databaseinto the webpage your browser sees.Any request to your server—for your author page, or that blog post you wrote a month ago, orfor the search results for the term “WordPress theme,” whatever—hits the WordPress factoryand requests what it wants right at the factory’s order window.This then sets off a bunch of procedures that are important but beyond the scope of this article,which end with a payload of posts coming back from the factory’s warehouse (the database)with the post or posts that we requested at the window ready to be made into a webpage.WP ShoutPage 8 of 39

The Three Core Concepts of WordPress ThemesOne Factory, Many Assembly Lines: The Template HierarchySo a bundle of posts, all ready to beprocessed, just rolled up to the backdoor of the factory. But the factory(through your theme) provides a lotof possible assembly lines to send itdown. It’s important for the properfunctioning of the factory that there’salways a line that can take the bundleof posts. This is why every WordPresstheme must havean index.php template file.But WordPress also makes it reallyeasy for you to divert certain bundlesof posts down different lines. This is what the template hierarchy does: it decides whichassembly line (which WordPress template file) should process a given bundle of posts.All lines do their work through the same basic means, called “The Loop”—so every line shouldtheoretically be built to handle any bundle. What the template hierarchy does, though, is make iteasy to change which line handles a particular page. For example, you can create a customtemplate for your author page, with elements unique to that page, by creating a file in yourtheme called author.php.Processing the Posts: The LoopAs we said, all valid assembly lines in the factory will process the bundle of posts through thesame basic method, called “The Loop.”Before I understood The Loop, I’d hear people mention it and think that it must be somecomplex topic that I couldn’t begin to understand. It’s actually almost exactly the opposite: TheLoop is a super-simple concept. It’s just sometimes hard for beginners to recognize it among allother PHP that’s going on in a given page template.We’re going to bring you up to speed in the next chapter, “Demystifying ‘The Loop’ inWordPress,” but for now let’s just check out the essentials, in these few lines of PHP:WP ShoutPage 9 of 39

The Three Core Concepts of WordPress Themesif ( have posts() ) :while ( have posts() ) :the post();// Post content hereendwhile;endif;This asks of the bundle, “Do you have posts in you?” If the bundle says yes, it then says “As longas you have posts, queue each one up and run this process for me.” (It’s the combinationof while ( have posts() ) : and the post(); which does this.)Then we’re going to run some process one each post. The process is missing in the exampleabove—it’d go where // Post content here currently sits. The process determines how yourposts will be displayed in WordPress. This is also where the “Post tags” you may recognize—the title(), the permalink(), are used. You’ll sometimes see these farmed out to aseparate file, in which case you’ll typically see get template part() (more on that in a coupleof chapters) used inside “The Loop,” rather than the template post tags. In either case, The Loopis just a simple way of WordPress running through all the posts which have been fetchedfrom the database, and processing them into a webpage to appear in the user’s browser.Factory Workers: Filters and Action HooksOne thing we’ve left out of this discussion, so far, ishow plugins and your theme’s functions.php file(which is essentially “your theme’s plugin”) can haveany effect on the factory’s processes. The method iscalled a “hook”—and I actually think it’s useful to thinkof them as literal hooks.What I mean by literal hooks is this: the factory (the core code of WordPress), must be keptimmaculate so that the factory’s overlords (the people who make WordPress’s core code) canreconfigure and expand the factory (release new versions of WordPress) when necessary. So theplugins and functions from your theme can’t stay inside the factory. They’ve got to wait outside.Factory workers, knowing the value of these outside contractors, have to go fetch anyone whohas requested to work with them on their task. So the outside contractors leave a note on ahook in the factory lobby for the workers to come get them, and the workers always check thathook as part of their work process.WP ShoutPage 10 of 39

The Three Core Concepts of WordPress ThemesWhat that actually looks like is:function new excerpt length( length) {return 200;}add filter('excerpt length', 'new excerpt length');Essentially, the add filter is our contractor new excerpt length leaving a note forthe excerpt length worker inside the factory. The excerpt length worker goes and getsthe new excerpt length contractor, who, in this case, takes the length value theexcerpt length worker hands him, and always hands back 200. excerpt length takes that200, and does with it what he was originally going to do with length. (new excerpt lengthis not necessarily the most inspiring independent contractor. Maybe he’s some sort of purist.)There are many other nuances about this, which we cover in a separate post called “A SimpleWay to Understand WordPress Hooks.” Have a look!Wrapping UpWe could obviously flesh out this analogy a lot more, and there are a ton of details that we’reglossing over. But hopefully you now feel like you have a basic understanding of the dynamic ofhow WordPress works with your theme to render the pages that are its product.WP ShoutPage 11 of 39

Demystifying “The Loop” in WordPressDemystifying “The Loop” inWordPressOne of the first things that typically stumps people trying to make WordPress themes is theconcept of “The Loop.” It’s the core concept of WordPress, so wrapping your head around it isdefinitely worth the upfront time cost. Our goal here is to make the concept clear first, and thento move on and show you how the code works.“The Loop” in Plain EnglishIn this section, I promise, no programming. We’ll just go over basic concepts.The main building blocks of of WordPress are “posts.” The terminology here gets a bit confusing,because WordPress by default has multiple post types, one of which is called “Posts,” and theother called “Pages.” For the rest of this piece, I’m going to use “posts” in the WordPress sense:“a long block of HTML saved in a database.” This includes Posts, Pages, and any other post typeyou can dream up.1WordPress is built around the idea that you’re writing and storing posts (just one last time:“Pages” are also posts) and it’s going to display your posts to the world on your website. This iswhere The Loop comes in. The WordPress Loop is the method WordPress uses to displayposts.Inside “The Loop,” you specify how you want those posts to be laid out. WordPress will reuse theformat you specify for all the posts it’s going to display on a given webpage. If there’s only onepost on the webpage—which is what we get when someone clicks onto a section of your sitecontaining either a page or just a single blog post—WordPress will still use the core concept ofThe Loop to process the (single) post into what you see when the webpage loads.As a last, hopefully unnecessary, language note: a “webpage” is not the same thing as a WordPress post. Rather, awebpage is a complete package of HTML content—header, footer, sidebar, post content, everything—sent to andrendered by your web browser. The Google homepage is a webpage, as is the homepage of your WordPress site.1Read the rest of this chapter and then come back to the following statement: “’The Loop’ processes WordPressposts in order to display them to users as webpages.” It should make sense.WP ShoutPage 12 of 39

Demystifying “The Loop” in WordPressThe use of The Loop is more obvious on your homepage, or your main blog page, whereWordPress cycle through, say, ten blog posts, reusing the format we’ve specified. The WordPressLoop is an “iterator”—programming jargon for something that repeatedly does something.Specifically, The Loop iterates over all the posts brought back from the database. No matterhow many posts there are going to be—1 or 100—you’ll always put the basic skeleton of theiterator in place, and WordPress will repeat it across all the relevant posts.The Minimal Loop ?phpif ( have posts() ) {while ( have posts() ) {the post();//// Post content here//} // end while} // end if ?phpif ( have posts() ) :while ( have posts() ) :the post();//// Post Content here//endwhile;endif;Two examples at once? Have I gone crazy?! No. I list them side by side because both examplesabove are identical in functionality, they just use different symbols to communicate it. You’ll seeboth formats frequently as you poke around WordPress themes, so I’ve included them both.Essentially, both if () {} and if () : endif; are ways we program conditions. Like manylanguages, PHP supports different syntaxes to specify conditional behavior. In the left examplewe’re saying, “If the condition inside the parenthesis is true, do what’s between the curlybrackets.” In the right case, we’re saying “If the condition in the parentheses is true, do whatcomes after the colon and before we tell you to stop with endif.”From the top—computers read just like we do—the first question of The Loop is a simple one:“Are there posts to display?” If there aren’t, WordPress will move on and ignore the rest of TheLoop (jumping past the } or endif;). If there are, then we proceed onward, where weencounter while. A while and an if have a lot of common, so if you understood the lastparagraph you’re most of the way there.The difference about while is that unlike an if, which asks its question once and thencontinues on, while continues to do what’s between the curly braces (or, in the example on theright, between :and endwhile) until its condition stops being true. What that means, in English,is that now that WordPress knows it has at least one post(s), it will keep “iterating” the stuff inthe while loop until it’s out of posts.WP ShoutPage 13 of 39

Demystifying “The Loop” in WordPressOK, one last issue: the stuff inside the while loop. There’s not much there in our example,because we’re keeping it light and only one thing must be in your while loop. That’sthe the post() “function call.” A stack of posts has come into the page, was verified to exist bythe if, and verified to have stuff in it by the while. Now, the post() is the worker who takeseach post in that stack, one by one, and makes it ready to use.In our giant factory, the post() is the truck-unloader who pulls one giant chunk of raw steelout so that we can start to fashion it into our giant gear. Because he’s only called once, he justunloads one piece, makes it ready for work, and sends the truck back around to the while loop.If the while inspector finds something more to work on in the truck, she’ll send the truck backaround and the posts() will take off another piece. If not, the truck will continue on and exit“The Loop.” This cycle will always continue until the truck is empty.An Example of The Loop in ActionMy hope is, after reading the functioning of the The Loop in programming-jargon-less terms,and then with the minimal programing jargon, you’ll be able to understand a real-worldexample. This example might be found in a very basic theme’s index.php file. ?php if (have posts()) { ? ?php while (have posts()) : the post(); ? li a href " ?php the permalink(); ? " ?php the title();? /a /li ?php endwhile;} ? One of the first things to realize about above example is that in the above section, everything wehad was PHP, but now we’re putting some HTML right along with it. Things that arebetween ?php and ? are considered valid PHP logic when run on the server; things that aren’tare just controlled by the surrounding PHP logic. That is: If the PHP that surrounds our HTMLsays the HTML should show up on the final page, it will. If it doesn’t, it won’t.Now a few things about the example are a bit weird. First, for learning’s sake, I’ve declaredmy if condition with curly braces and my while condition with a colon and an endwhile. Thiswill function perfectly, it’s just a bit confusing to the reader, so best not to do it in real life.Similarly, in the last section we had the post() on its own line and here it’s sharing the linewith the existing while condition. Again, this is totally functional PHP and will work withoutproblem. It’s just an example of the ways in which real-world uses of The Loop may vary.WP ShoutPage 14 of 39

Demystifying “The Loop” in WordPressThe truly new stuff though, is that middle line, the one that starts li . The HTMLtags li /li surround “list items,” just as a /a surrounds a link.Essentially, in WordPress, you use functions like the permalink() and the title() to getdata about the current post. These functions are called template tags (check out our laterchapter on them!), and they just output the data that they describe right into the HTML thatsurrounds them. So once filled in by The Loop, each post that is being iterated over in this loopwould spit out something like: li a href he-loop-inwordpress/" Demystifying "The Loop" in WordPress /a /li This is a list ( li /li ) containing a link ( a /a ) that points to the postusing the permalink(), and displays the title(). Many other WordPress template tags doexist, like the content(), which displays the contents of the post, and the excerpt(), whichdisplays either the first part of the post, or the excerpt that is manually set for the entry.Onward to New HeightsThere are no doubt details about the The Loop I failed to explain sufficiently. But I hope I gaveyou a good simple overview of the how the whole thing works to transform posts intowebpages. Understanding The Loop is one of the most powerful pieces in starting tounderstand how WordPress works.WP ShoutPage 15 of 39

Understanding the WordPress Template HierarchyUnderstanding the WordPressTemplate HierarchyOne of the simpler and more powerful concepts that runs underneath WordPress themes is thetemplate hierarchy. It’s super powerful and can make your life much easier as you build out atheme for your site. And it’s not all that complex, so once you get the idea you’ll find working onthemes much easier.The Problem that Leads to the HierarchyWordPress wants its themes to be two things: easy to customize and hard to break. Whenthemes do end up having both these qualities, it’s part of what makes WordPress great—butbalancing them is something that takes some thought and insight.To make themes hard to break, WordPress can always render pages by falling back toindex.php and The Loop. This has two parts: use of The Loop, and the existence ofindex.php as a fallback.First, every template file uses The Loop. There’s no such thing as a “page Loop” and a “blog postLoop” and an “author page Loop.” It’s all one thing, and this abstraction makes WordPress muchbetter able to guarantee that any given template file can render any given content.Second, every page can always fall back to index.php in the absence of more specific templatefiles. Every WordPress theme needs an index.php file, and index.php should be running TheLoop. This allows WordPress to use index.php anytime it doesn’t have a better-fitting file torender a particular page.Put together these two elements makes a WordPress theme hard to break: even for obscurenew content types, WordPress will always be able to fall back to index.php and The Loop tocatch and render them.To make WordPress easy to customize, WordPress has built up a large choice tree ofadditional template options on top of index.php. WordPress can always counton index.php being there: but it’ll try to find a better, more specific template file to use if oneexists. For example, I want to change the page layout for when visitors are just viewing a singleWP ShoutPage 16 of 39

Understanding the WordPress Template Hierarchypost, I can make a file called single.php, with The Loop inside of it, and WordPress will usethat when it thinks there’s only one post on the page. This is powerful.The Dynamics of the Template HierarchyAs we’ve said, WordPress has built up some really powerful choice trees.Let’s say you want to customize the way your category archive—the listing of multiple postsfrom a single category—will look. If you’ve got an index.php in place, the first option you haveis to create or modify archive.php. This is the template that WordPress uses for any archive,so you could customize that if you also want your customizations to apply when your visitorclicks onto archives based around tags, or the month of publication.If you don’t like that, we can then continue down the path: the next option is that we can createor modify category.php. This will be used for any category archive, but only for categoryarchives—not archives by date, tag, author, etc.WP ShoutPage 17 of 39

Understanding the WordPress Template HierarchyBut if you now decide that you only want your changes to apply to one category archive—forexample, “Poems”—you’ve got a few more options. You can create a new template file calledcategory-poems.php or, if you figure out the category number, category-32.php, andWordPress will use that to render the view when someone click a link to the post categorywhose category slug is poems (which, if you’ve done it right, should correspond to your “Poems”or “Poetry” post category).As simple as this dynamic is, you may be able to imagine its considerable power. One thing itimplies is that customization and improvements can be made on the fly as you build out aWordPress theme. start with a simple index.php, get it set up just how you like, and thentweak it for all the different ways that WordPress will possibly find itself displaying your content.Seeing the Whole HierarchyOnce you understand the core concepts above, the next step is just to learn the various ways ofstacking WordPress templates and creating new ones.Listing out the specific layout of each tree that WordPress looks at for each type isn’t all thatuseful here, so I’ll refrain. I promise it’d only bore both of us. But there are a few exemplary waysto see and understand this data when you need to reference it: Template Hierarchy on the WordPress Codex: The Codex is the canonical source for allyour information about WordPress. Learn to love it. The page is quite long and detailed,which makes for somewhat dull reading, but makes it super valuable as a reference. Youcan easily CMD/CTRL F for whatever you specific problem is—“single taxonomy” forexample—and quickly find a gre

WordPress developers and empowered WordPress site owners. Mastering the Fundamentals of WordPress Themes aims to help you become one of them. We’ll be lifting the hood on WordPress themes—so you can start to see how they work, how they fit together, and how you can build and modify them