Template tags are used within themes to retrieve content from your database. The content can be anything from a blog title to an entire sidebar. Template tags are the preferred way to attract content to your template for the following reasons:
- They can print dynamic content;
- Can be used in multiple theme files; And
- They divide the theme into smaller, more understandable sections.
The template tag is simply a piece of code that tells WordPress to get something from the database. It is divided into three components:
- PHP code tag
- WordPress function
- Optional parameters
You can use the template tag to call another theme file or some information from the database.
For example, the template tag get_header() tells WordPress to get the header.php file and include it in the current template file.
Similarly, get_footer() tells WordPress to get the footer.php file.
There are also other types of template tags:<?php the_title(); ?>
Tells WordPress to get the title of the page or post from the database and insert it.<?php bloginfo( ‘name’ ); ?>
Tells WordPress to get the blog title out of the database and include it in the template file.
If you look closely at the last example, you will also see that there is a parameter in parentheses. Parameters allow you to do two things:
- Ask for specific pieces of information and
- Format information in a certain way.
By encapsulating all the code for a specific piece of content, template tags make it very easy to include different parts of the template in the theme file as well as maintain the theme.
It’s much easier to create a single header.php file and have all of your theme templates like single.php, page.php, front-page.php etc. refer to one theme file using get_header() rather than copying and pasting the code into all theme file. It also makes maintenance easier. When you make a change in your header.php file, the change is automatically transferred to all other theme files.
Another reason to use template tags is to display dynamic data, i.e. data from the database. On HTML sites, you can include the title tag manually, like so:
<title>My Personal Website</title>
the_content() the_title(); the_excerpt() next_post() previous_post() wp_list_cats() wp_list_pages() bloginfo ( 'version' ) ; bloginfo( 'name' ); get_header();