wp_theme_has_theme_json()WP 6.2.0

Проверяет, есть ли файл theme.json в активной теме или в её родительской теме.

Функция помогает понять, использует ли тема настройки Global Styles через theme.json. Это может быть полезно, когда нужно по-разному подключать стили, настройки редактора или совместимость для классических и блочных тем.

Сначала проверяется директория дочерней темы. Если там нет theme.json, проверяется директория родительской темы.

Путь к файлу проходит через фильтр theme_file_path, поэтому его можно изменить. Результат кэшируется для текущей темы, но кэш не используется, если включён режим разработки темы - wp_is_development_mode().

Работает на основе: get_stylesheet_directory(), get_template_directory()
Основа для: wp_get_global_stylesheet()
Хуки из функции

Возвращает

true|false.

  • true — если файл theme.json найден в активной или в родительской теме.
  • false — если файл не найден.

Использование

wp_theme_has_theme_json();

Примеры

0

#1 Функция проверки наличия файла theme.json в текущей теме или ее родительской теме

/**
 * Checks whether a theme or its parent has a theme.json file.
 *
 * @since 6.2.0
 *
 * @param WP_Theme $theme Theme object.
 *
 * @return bool True if theme or its parent has a theme.json file, false otherwise.
 */
function wp_theme_has_theme_json( $theme ) {
	$theme_json_file = $theme->get_stylesheet_directory() . '/theme.json';
	if ( file_exists( $theme_json_file ) ) {
		return true;
	}

	if ( $theme->parent() ) {
		$parent_theme = wp_get_theme( $theme->parent() );
		if ( $parent_theme && $parent_theme->exists() ) {
			return wp_theme_has_theme_json( $parent_theme );
		}
	}

	return false;
}
0

#2 Проверка поддержки theme.json

Проверим, есть ли у текущей темы файл theme.json.

if ( wp_theme_has_theme_json() ) {
	echo 'Тема использует theme.json.';
} else {
	echo 'Файл theme.json не найден.';
}
0

#3 Подключение стилей только для тем без theme.json

Пример показывает, как подключить дополнительный CSS только для темы, у которой нет theme.json.

add_action( 'wp_enqueue_scripts', 'prefix_enqueue_classic_theme_styles' );

function prefix_enqueue_classic_theme_styles() {
	if ( wp_theme_has_theme_json() ) {
		return;
	}

	wp_enqueue_style(
		'prefix-classic-theme',
		get_stylesheet_directory_uri() . '/classic-theme.css',
		[],
		'1.0.0'
	);
}
0

#4 Проверка в админке

Можно использовать функцию, чтобы показать уведомление администратору, если тема не содержит theme.json.

add_action( 'admin_notices', 'prefix_theme_json_admin_notice' );

function prefix_theme_json_admin_notice() {
	if ( wp_theme_has_theme_json() ) {
		return;
	}

	?>
	<div class="notice notice-info">
		<p><?php esc_html_e( 'В текущей теме не найден файл theme.json.', 'textdomain' ); ?></p>
	</div>
	<?php
}
0

#5 Изменение пути к theme.json через фильтр

Фильтр theme_file_path позволяет изменить путь к файлу, который будет проверяться.

add_filter( 'theme_file_path', 'prefix_change_theme_json_path', 10, 2 );

function prefix_change_theme_json_path( $path, $file ) {
	if ( 'theme.json' !== $file ) {
		return $path;
	}

	return get_stylesheet_directory() . '/config/theme.json';
}

Список изменений

С версии 6.2.0 Введена.

Код wp_theme_has_theme_json() WP 7.0

function wp_theme_has_theme_json() {
	static $theme_has_support = array();

	$stylesheet = get_stylesheet();

	if (
		isset( $theme_has_support[ $stylesheet ] ) &&
		/*
		 * Ignore static cache when the development mode is set to 'theme', to avoid interfering with
		 * the theme developer's workflow.
		 */
		! wp_is_development_mode( 'theme' )
	) {
		return $theme_has_support[ $stylesheet ];
	}

	$stylesheet_directory = get_stylesheet_directory();
	$template_directory   = get_template_directory();

	// This is the same as get_theme_file_path(), which isn't available in load-styles.php context
	if ( $stylesheet_directory !== $template_directory && file_exists( $stylesheet_directory . '/theme.json' ) ) {
		$path = $stylesheet_directory . '/theme.json';
	} else {
		$path = $template_directory . '/theme.json';
	}

	/** This filter is documented in wp-includes/link-template.php */
	$path = apply_filters( 'theme_file_path', $path, 'theme.json' );

	$theme_has_support[ $stylesheet ] = file_exists( $path );

	return $theme_has_support[ $stylesheet ];
}