Skip to content News Background
Webbed Feet UK, web developers in Salisbury, Wiltshire

Using PHP variables within a WordPress theme to create custom design

WordPress is written in PHP; therefore some knowledge of PHP is required to create a bespoke skin. More sophisticated designs may require PHP variables to be passed and used within the theme. This article offers a brief narrative on how to display different design aspects depending on the post subject published on your WordPress blog. We can do this with the use of WordPress custom fields and PHP variables.

First, use the custom fields’ facility to declare values

You can create custom fields in WordPress for each blog entry you create, so the first step is to ensure you create a custom field and declare its value. So, for example, we could create a custom field called “section” and then give the custom field the value of “fat_loss” if the post is to be published within the fat loss category on your web site.

Now open up wp-contentthemesdefaultheader.php (if editing the default theme)

You can store the value of this custom field by placing the following code within the header:

$section = get_post_meta($post->ID, ‘menu’, true);

$section is now stored with the value “fat_loss” when viewing the blog entry you have just published, so we can now use this variable to ensure the page content is specific to this section. For example, we can display things on the page, specific to this section, by wrapping any code within:

If((isset($section)) && ($section == ‘fat_loss’)) {
// code in here
}

You can use this code to display specific navigation, colour schemes (you could create specific CSS files) and images depending on the subject of your post!

Ensuring the variable is accessible from all pages

Declaring and setting the variable is not the only change we have to make, however. If we declare the variable within the header we will not be able to refer to it within the footer, side bar etc as these pages are called using PHP functions which have not had the variable passed into. We must therefore make some changes to the way files are included on the pages so our variable is global and can be called on any of the pages. To do this we change:

get_header(); to include (TEMPLATEPATH . “/header.php”);
get_footer(); to include (TEMPLATEPATH . “/footer.php”);
get_sidebar(); to include (TEMPLATEPATH . “/sidebar.php”);
etc…

The variables you create within the header should now be callable within the other pages of WordPress.

This article is categorised within:

Website Design WordPress