How do I get the parent theme’s version in a child theme?
I want to use it when loading the parent theme’s stylesheet.
Here’s how I load the stylesheets in the child theme’s functions.php
file:
function sometheme_enqueue_styles() {
// Get parent theme version
$parent_theme_version = wp_get_theme()->parent()->get( 'Version' );
// Load parent theme stylesheet
wp_enqueue_style( 'sometheme-style', get_template_directory_uri() . '/style.css', array(), $parent_theme_version );
// Load child theme stylesheet
wp_enqueue_style( 'sometheme-child-style',
get_stylesheet_directory_uri() . '/style.css',
array( 'sometheme-style' ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'sometheme_enqueue_styles', 11 );
However, this will use the child theme’s version for both stylesheets…
I have also tried this:
$parent_theme = wp_get_theme('sometheme');
$parent_theme_version = $parent_theme->get( 'Version' );
…and this:
$parent_theme = wp_get_theme(get_template());
$parent_theme_version = $parent_theme->get( 'Version' );
But again, the parent theme version keeps getting the version from the child theme.
Solution
It turns out that both wp_get_theme()->parent()->get( 'Version' );
and wp_get_theme()->parent()->Version;
works.
The problem was that the parent theme was using $theme_version = wp_get_theme()->get( 'Version' );
as well, which means that it will use the child themes version.
Since I own the parent theme, I changed the parent theme to wp_get_theme('sometheme')->get( 'Version' );
so that it always uses its own version.
That way, I can use either wp_get_theme()->parent()->get( 'Version' );
or wp_get_theme()->parent()->Version;
in the child theme.
2 Answers
In the WP_Theme class, the get
method gives you a sanitized theme header. You cannot use it to extract a property. Actually you don’t need to, as you can access it directly like this:
// get the parent object
$parent = wp_get_theme()->parent();
// get parent version
if (!empty($parent)) $parent_version = $parent->Version;