Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 2 • The WordPress Syntax 31


USING THE TEMPLATE TAGS


Although WordPress is written in PHP, it is in fact a framework in itself. You can use PHP to
do stuff with your WordPress theme or plugin, but most of the functionality is managed with
template tags. If you open a theme file (just about any file with the extension .php, such as
index.php or single.php), you’ll find a lot of PHP-like functions, such as this one:


<?php bloginfo( 'name' ); ?>


This is a template tag, and it outputs the blog’s name. The PHP part, which consists of <?php
at the beginning and ;?> at the end, tells WordPress to process whatever’s inside it — in this
case, the template tag bloginfo(). Within the parentheses, you’ll find the parameter,
passed inside quotation marks. In other words, 'name' is the parameter in this example
(which would output your blog’s name).


The following example uses get_template_directory_uri() to get the URI (without a
trailing slash, as you can see) for the template folder so that you can reference an image. The
following code outputs an image called smashing.gif in a theme file:



You’ll recognize the img HTML tag. get_template_directory_uri() outputs the path
to the theme’s folder. Then you just add the smashing.gif filename to complete the path, and
you’ve got a potentially working image path in your theme. Of course, you would need the
image in the theme folder as well.


So template tags are basically PHP functions that can handle parameters to do different
things. Some have default values, others don’t, and some have more settings for you to play
with than others. Most of them will work anywhere in your WordPress theme files, but some
need to be within the loop. (The loop is basically the code that outputs the content, such as
posts or pages. Loops are examined in the next chapter.)


You’ll find a complete listing of template tags in the Codex at http://codex.wordpress.
org/Template_Tags. Consult it whenever you need to do something out of the ordinary
within your themes or when you want to alter things in an existing theme. Each template tag
is described, along with usage and sample code to help you understand it. This is the beauty of
WordPress: You can actually copy and paste your way to a different result without knowing
any PHP at all.


THE INCLUDE TAGS


There are a couple of template tags that you’ll find in just about any theme template file. The
include tags are simply PHP include functions used to load files, which in turn might output
the content of the necessary files within your theme. In other words, they are just a way to
make it a bit easier to grab that header, footer, and sidebar:


<?php get_header(); ?>
<?php get_footer(); ?>
<?php get_sidebar(); ?>

Free download pdf