Conditional Variables and Database Queries in WordPress

Over the years, WordPress blogs have grown from simple websites full of basic content to categorized, tagged, archived, and well-organized websites that contain nearly ten years of blog posts, dynamic pages, and other information. There’s no doubt that the 60 million users who use WordPress software have taken the “content management system” label to heart. Because WordPress is now responsible for managing such a large amount of each website’s information, many people have found it to be almost impossible to use the built-in theme development system to properly divide that content into separate pages, sometimes with distinct designs, without creating a needlessly complex and expansive file structure.

Indeed, the most common way of splitting content into unique template designs is one that requires a new file for each page, causing the server to slow down as the WordPress software taxes its resources. Luckily, the WP team has included a way to alter templates “on the fly” using database queries and conditional variables.

Advantages of conditional variables and database queries

The big advantage to using both conditional variables and database queries within a WordPress template is that the file can be made to present completely unique design elements, or even distinct blocks of content, without the user having to create an extensive series of templates which cater to each individual category or author. It essentially enables instant processing of information, and it brings the dynamic flavor of Dashboard-created WordPress pages into the typically static PHP files which constitute a traditional WordPress theme. Because these template files remain singular, and are processed and rendered on the fly, the server experiences no real hit to its performance. Page loading times remain relatively quick and consistent when using this method, and the WordPress blog won’t have to sacrifice frustrated readers who simply don’t have time to wait for the eighth category page to be pulled from the server and filled with content.

example of conditional variables and database queries code

Below, WordPress developers and designers will learn how to leverage database queries and conditional variables within their templates in order to create a single file which displays multiple blocks of content. This requires a pretty solid working knowledge of PHP and WordPress variables, and, for design purposes, these users should have a good grip on how to employ XHTML and the CSS which turns it into something aesthetically pleasing.

Let’s get started.

Step 1: How Content is Separated in a World Without Conditional Variables

When WordPress released some of its first software versions, in 2003, the company didn’t really support using database queries and conditional variables in its template files. It instead encouraged users to develop custom template types by adhering to the WordPress file hierarchy, which enabled custom designs and blocks of content by creating a new file for each category, author, or dynamic page. This was done by making the index.php file the number one template file for the installation. By default, any and all content created within WordPress displays using the index.php file. Next, the hierarchy processed individual template files like archive.php and category.php and page.php. This allowed authors to create unique designs that would apply to all archive pages, all category pages, or all dynamic pages created in the WordPress Dashboard.

That might be enough for most users, but WordPress understood that many advanced users would need more flexibility. For this reason, the developers included an even more intricate way of styling individual pages throughout the WordPress ecosystem. Administrators or designers could create page templates that were specific to one category, page, or author, by appending the template name with the ID number of the respective element. For example, a category named “General” which had an ID number of “1,” could be given an entirely unique appearance by creating the file category-1.php. Likewise, user ID numbers could be used to create templates like author-4.php.

Using the file hierarchy, designers could easily give each page a unique appearance simply by creating a series of customized templates. As mentioned earlier, however, this method significantly burdened the server and was considered inefficient. As the developers behind WordPress looked to leverage database interaction and PHP variables, they decided that using conditional variables and actual queries in a template file would be the perfect way to alleviate the server burden and promote the now widely held view that themes should be compact and dynamic in nature.

Step 2: Making the Transition and Learning about Conditional Variable Use in Templates

Unfortunately, using conditional variables and raw database queries in WordPress does have a significant usability drawback. It requires users to get in touch with some of the most raw elements of PHP programming, and it prompts a crash course in WordPress variable use and template semantics. For users who are accustomed to simply developing multiple template files, it can be a bit confusing to know when to deploy these queries and variables, and where to place them within a template file.

The first step is simply knowing the category, author, or page ID number which will be used to query the database and pull out the right section of data. This information can be found in the WordPress Dashboard, listed right alongside the relative page, author, or category, in older installations. In more recent releases, this information can be found in the raw browser URL which is displayed when editing one of these content areas. Look for a URL fragment like category_id=3. This is the number that will be used in the relevant database query.

In template files, a conditional variable is setup to essentially say “if the category ID is 3, then display this information. If the category ID is 4, display this information instead.” This process is repeated over and over again until every category has been addressed. Multi-category conditional statements can also be used, in order to say something like “for categories 3, 6, 9, 10, and 12, display this template. For others, display the standard template.” When conditional statements are viewed as mere instructions, they’re far easier to understand. Here’s how an author template can be customized to display a custom template for the administrator user, while displaying a standard template for all of the regular authors within an installation by using a simple conditional variable within a database query:

<?php $post = $wp_query->user;
if ( is_author( '1' ) ) {
echo( ' ADMINISTRATOR TEMPLATE GOES HERE' );
} else {
echo( 'GENERAL AUTHOR TEMPLATE GOES HERE' );
}
?>

The above query could be easily extended, instructed to display a different template for each author’s ID number. This would involve creating an is_author statement for each of the author IDs within a WordPress installation. It’s important to remember never to remove the “else” variable when using a custom database query, however. This will allow a default template to be shown in case a new author is added and the site’s administrator or designer forgets to create a custom version of the template for that new author. It ensures maximum usability and compatibility with the site’s changes going forward, and it’s an essential part of any conditional database query within a WordPress template.

Step 3: Learning How to Use Queries to Control the Output of a WordPress Loop

The instructions above can be applied to every page, author, or category template within a WordPress theme, and that’s great. However, there is an easier way to customize the output of a template without using conditional variables. Many WordPress users aren’t aware that the famous WordPress Loop is actually subject to the whims of a mere database query. By default, it shows all content, posted within any category, in ascending or descending chronological order. With a little handy-work, though, the WordPress Loop can be tightly controlled and made to display only one series of entries.

This should be done within a template such as index.php, where it might be necessary to create categorized lists of posts rather than throwing them into the same central column of content indiscriminately. It can also be done on archive pages to separate the archives into easier-to-read segments. It’s really up to the WordPress designer where to use this unique construction; the important part is dimly learning how to control the output of the Loop.

When turning a standard WordPress Loop into one which is controlled by a query within the template file, it’s important to remember the process requires a certain syntax. The WordPress Loop, in this instance, will actually become secondary to the database query which controls which entries it can display. For that reason, the actual query itself must be placed into the template immediately before the WordPress Loop code is inserted. A basic example looks like the following:

<?php query_posts('category_name=kittens&posts_per_page=15'); ?>

<?php while (have_posts()) : the_post(); ?>

TYPICAL LOOP CONTENT AND VARIABLES ARE PLACED HERE.

<?php endwhile;?>

The example above will display the fifteen latest posts which were placed into the “Kittens” category. This is done by using the category’s so-called “short name,” which is typically the same as its permalink URL. For those unsure of the category’s short name and it’s permalink URL, this information can be found in the WordPress Dashboard category management area, or designers can simply click on a category link and examine the resulting permalink URL in their browser window.

One thing worth noting is that the example above can only be used for the first query-based WordPress Loop presentation in any given template. If multiple queries are being used to display multiple categories of content in a single page, those new queries must be given a unique name so that they are processed separately from the one listed above. Failure to distinguish these queries from each other will almost certainly result in nasty and unsightly PHP errors being printed to the end user, so it’s important to master the use of multiple, custom queries in a template file.

If the query above was one of many, and the author also wanted to display columns of entries that were placed into categories like “puppies” and “ponies,” among others, they would create a new query, assign it a category name variable, and then actually give the query itself a distinct name that separates it from all of the others on the page. That would look like the following example:

<?php $puppy_query = new WP_Query('category_name=puppies&posts_per_page=15'); ?>

<?php while ($puppy_query->have_posts()) : $puppy_query->the_post(); ?>

In this example, the query is assigned a variable in the first line of code. That variable must then be used in the opening line of the resulting WordPress Loop in order to have that Loop distinguish itself from the others on the page. This is a two-part process; failure to bring the query name into both the original query statement, as well as into the WordPress Loop’s opening line of code, will cause the page to print errors to the end user.

Step 4: Bug Testing and Deploying the New Templates

With the query-based template files now complete, it’s time to save and upload each modified file to the server and test the new template on the production website. Make sure that each author page or category page is displaying the correct information for each category name or author ID number, and monitor page loading times and overall performance while it performs these operations. When everything is verified as working correctly, the process is complete and the theme can be considered optimized, efficient, and fully dynamic.

Author: (40 Posts)

Vladislav Davidzon is the principal of US-based online marketing consultancy Vladislav Davidzon & Associates, developing integrative solutions through high impact search engine optimized WordPress websites for socially responsible customers of all sizes around the world.

Comments