Why We Should Set the $content_width Variable in WordPress Themes

WordPressPosted on

The $content_width global variable was introduced in WordPress 2.6. Using it, we can set a maximum with for our content.

It is a theme feature which helps us to control our content width for images, videos and embeds. If you used _s starter theme or browsed through any official WordPress theme, you saw it in the functions.php. In today’s responsive design, it is not the most necessary tool for the images but still useful because of the other media formats.

An excellent addition is that after the theme activation, it is also set the large image size to this value. It is also accessable for plugins. If you want to build a valid theme – checked by Theme Check – you should set up this parameter.

Set the $content_width in Your Theme

To set the value for it, you must declare it as a global variable. If you add it into the functions.php add it at the top of the file.

if ( ! isset( $content_width ) )
    $content_width = 640;

A more sophisticated method which is used in _s:

function pine_content_width() {
    $GLOBALS['content_width'] = apply_filters( 'pine_content_width', 640 );
}
add_action( 'after_setup_theme', 'pine_content_width', 0 );

Here you can see we added it using the after_setup_theme action on low priority. We used the $GLOBALS array and used a filter to declare the value. The filter is needed if you want to override it later like in a child theme.

If we use different page templates with different width, we can also modify the maximum content width — the best way to achieve it to use the template_redirect action.

function pine_change_content_width() {
    if ( is_page_template( 'full-width.php' ) )
        $GLOBALS['content_width'] = 800;
}
add_action( 'template_redirect', 'pine_change_content_width' );

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in WordPress category