Variable Width Pages For Your Theme

Starting with WordPress version 3, WordPress Theme Developers can now set a global variable called $content_width to inform WordPress of the desired width of the page. This values is used when displaying full-width images and for videos.

But what if you have different widths for different pages? You need a way of indicating to the WordPress system that the page width can change depending on the theme page being used. So here’s a small code sample that can detect different page templates and change the $content_width accordingly.

<?php
// set content width depending on page template
function d3j_set_content_width()
{
	global $post;
	$template = 'default';
	if ( isset( $post ) && isset( $post->ID ) )
		$template = get_post_meta( $post->ID, '_wp_page_template', TRUE );
	switch ($template) {
	case 'default':
	default:
		$width = 584;		// default width (taken from twentyeleven theme
		break;
	case 'showcase.php':
		$width = 480;
		break;
	case 'sidebar-page.php':
		$width = 500;
		break;
	}

	// use additional conditions to set page width

	if ( is_attachment() )
		$width = 584;		// use this width for attachment pages

	global $content_width;
	$content_width = $width;	// set $content_width to calculated value
}
add_action( 'wp_head', 'd3j_set_content_width', 1 );

The hook is on the ‘wp_head’ action, as this is the point in time that WordPress needs to know the width of the page. It does this at a priority of 1, so that other functions operating on the same hook will have the modified value already set.

The function determines the page width by looking at the selected page template, according to the _wp_page_template meta data value that WordPress uses to store which page template is used when displaying the page. The is the mechanism used by “standard” themes, such as Twentyeleven.

If you’re using a different theme framework, your page template may be stored in a different way. For example, the Genesis Framework uses the meta value _genesis_layout. If you’re using that framework, you will need to obtain the different value and modify the switch-case appropriately, checking for values like ‘content-sidebar-sidebar’.

As you see on Line 24, you can also use additional theme helper functions to enable different widths on specific pages. Other test functions such as the is_author(), is_front_page(), is_404(), etc. can be added to the list.

With a little careful thinking and planning, you can achieve a theme that is very flexible in its ability to display images and videos and accommodate theme settings. You’ll run into some issues if you’re using a theme or framework that uses non-standard settings, but those are not too difficult to work through. Just be careful to fall back to a default width setting in the case that your page does not have this meta data set already.

Leave a Comment

Your email address will not be published.