Categories for Pages
One of the fundemental design axioms for my site (my Theme) was that I wanted to cater for sites that had Corporate pages and Technical / Information pages, and that the Corporate pages would have a completely different look and feel. These corporate pages I actually termed site-pages, and, well given you are here, you have probably already noticed that the:
- Home
- About
- Privicy Policy
- Contact Me
pages are formated consistently, but completely different from the other pages.
I could (probably) achieved this using different templates, but I wanted this feature to be coded into the theme, not something the User had to work out for themseleves.
Coding in a Category in a Theme
The following code included in the theme set_up will enable categories for Page post-types. However this will not affect which template file is used as the template heirarchy does not search categories for page post-types.
//Add site-page category for post-type 'page';
if (file_exists (ABSPATH.'/wp-admin/includes/taxonomy.php'))
{
require_once (ABSPATH.'/wp-admin/includes/taxonomy.php');
}
wp_insert_category(
array(
'cat_name' => 'Site Page',
'category_description' => 'This category identifies thos pages that will use the site-page template',
'category_nicename' => 'site-page',
'taxonomy' => 'category'
)
);
Assigning Page Template based on Category
To implement the asignment of a different page template for different categories you will need to include something along the line of the following code. What this code is doing is, for posts for which âis_site_pageâ returns true, the template file âcategory-site-page.phpâ is added into the template search heirarchy.
/**
* Insert category-site-page template into template search heirarchy.
*/
function q5_category_site_page_template( $templates = '' )
{
$page = get_queried_object();
if (is_site_page($page))
{
if ( ! is_array( $templates ) && ! empty( $templates ) )
{
$templates = locate_template( array( "category-site-page.php", $templates ), false );
}
elseif ( empty( $templates ) )
{
$templates = locate_template( "category-site-page.php", false );
}
else
{
$new_template = locate_template( array( "category-site-page.php" ) );
if ( ! empty( $new_template ) )
{
array_unshift( $templates, $new_template );
}
}
}
return $templates;
}
add_filter( 'page_template', 'q5_category_site_page_template' );