WordPress quick tip #4 – Display the version of a WordPress theme using a function

This tutorial covers the steps needed to retrieve and display the version number of a WordPress theme.

The process, which is very simple, makes use of the existing function used by the WordPress admin interface to display data about theme on the Manage themes page in the site admin.

The code takes the form of a very simple function, which needs to be placed in the theme’s functions.php file:

function my_site_Version()
$theme_data = get_theme_data(get_bloginfo('template_directory') . '/style.css');
return $theme_data['Version'];
}

The function makes use of the get_bloginfo() function to fetch the file path to the theme’s style.css file. This in turn is referenced by the get_theme_data function, which references the data in the comments at the top of the style.css file.

Having located the theme information, the $theme_data variable can be used to retrieve the required theme information, not just the theme version. In this case we are after the ‘version’. Prefacing $theme_data with return outputs the data when the function is called.

That’s the hard work done.

Displaying the theme version number

Having found the data there are a couple of options available for displaying it on your site. First, place it anywhere in a theme file simply by calling the function:

<?php my_site_Version(); ?>

With the addition of a single line of code after the function, it’s possible to reference the data via a shortcode, which of course can be placed within the content of posts or pages. After the closing curly bracket of the function add the following:

add_shortcode('msv', 'my_site_Version');

add_shortcode() is the WordPress function for creating a shortcode. The first of the two parameters inside the brackets sets the name by which the shortcode will be referenced from within a post. The second calls the function, in this case my_site_Version(). To display the theme version via a shortcode, simply place [msv] in the content of a post or page.

The complete code

The completed code looks like this:

// SITE VERSION SHORTCODE
//
function my_site_Version()
$theme_data = get_theme_data(get_bloginfo('template_directory') . '/style.css');
return $theme_data['Version'];
}
add_shortcode('msv', 'my_site_Version');

Resources

Tags: