Get Theme Status
Overview
Check whether a theme is active by slug. The helper matches the active theme and its parent theme, so it works for child theme installs as well.
Use the generic helper for any theme slug, or the explicit helpers for common themes used in our builds.
Variants
- Procedural
- OOP
<?php
/**
* Theme status helpers.
*/
/**
* Check if a theme is active (child or parent).
*
* @param string $slug Theme slug.
* @return bool
*/
if ( ! function_exists( 'mac_is_theme_active' ) ) {
function mac_is_theme_active( string $slug ): bool {
$slug = sanitize_key( $slug );
if ( $slug === '' ) {
return false;
}
/** @var array<string,bool> $cache */
static $cache = [];
if ( isset( $cache[ $slug ] ) ) {
return $cache[ $slug ];
}
$theme = wp_get_theme();
if ( ! $theme instanceof WP_Theme ) {
return $cache[ $slug ] = false;
}
if (
$theme->stylesheet === $slug ||
$theme->template === $slug
) {
return $cache[ $slug ] = true;
}
$parent = $theme->parent();
if ( $parent instanceof WP_Theme ) {
if (
$parent->stylesheet === $slug ||
$parent->template === $slug
) {
return $cache[ $slug ] = true;
}
}
return $cache[ $slug ] = false;
}
}
/**
* Explicit theme status helpers.
*/
// Bricks
if ( ! function_exists( 'mac_is_bricks_theme_active' ) ) {
function mac_is_bricks_theme_active(): bool {
return mac_is_theme_active( 'bricks' );
}
}
// Etch
if ( ! function_exists( 'mac_is_etch_theme_active' ) ) {
function mac_is_etch_theme_active(): bool {
return mac_is_theme_active( 'etch-theme' );
}
}
<?php
/**
* Theme status helpers.
*
* @package mac-core
*/
declare(strict_types=1);
namespace MacCore\Utils;
use WP_Theme;
/**
* Theme status helpers.
*/
final class GetThemeStatus
{
/** @var array<string,bool> */
private static array $cache = [];
/**
* Generic theme active check by slug.
* Matches active or parent theme.
*/
public static function isThemeActive(string $slug): bool
{
$slug = \sanitize_key($slug);
if ($slug === '') {
return false;
}
if (isset(self::$cache[$slug])) {
return self::$cache[$slug];
}
$theme = wp_get_theme();
if (! $theme instanceof WP_Theme) {
return self::$cache[$slug] = false;
}
if ($theme->stylesheet === $slug || $theme->template === $slug) {
return self::$cache[$slug] = true;
}
$parent = $theme->parent();
if ($parent instanceof WP_Theme) {
if ($parent->stylesheet === $slug || $parent->template === $slug) {
return self::$cache[$slug] = true;
}
}
return self::$cache[$slug] = false;
}
/* -------------------------
* Explicit helpers
* ------------------------- */
public static function isBricksThemeActive(): bool
{
return self::isThemeActive('bricks');
}
public static function isEtchThemeActive(): bool
{
return self::isThemeActive('etch-theme');
}
}