函数文档

wp_get_theme_preview_path()

💡 云策文档标注

概述

wp_get_theme_preview_path() 是一个 WordPress 函数,用于过滤博客选项以返回预览主题的路径。它检查用户权限和主题错误,根据当前过滤器返回模板或样式表路径。

关键要点

  • 函数用于获取预览主题的路径,基于用户权限和查询参数。
  • 参数 $current_stylesheet 可选,默认 null,表示当前主题的样式表或模板路径。
  • 返回值为字符串,表示预览主题的样式表或模板路径。
  • 函数内部检查 current_user_can('switch_themes') 权限,若无权限则直接返回 $current_stylesheet。
  • 通过 $_GET['wp_theme_preview'] 获取预览主题标识,使用 wp_get_theme() 获取 WP_Theme 对象。
  • 根据 current_filter() 判断是 'template' 还是其他过滤器,分别调用 get_template() 或 get_stylesheet() 获取路径。
  • 使用 sanitize_text_field() 和 wp_unslash() 进行安全处理,并检查 is_wp_error() 处理错误。

代码示例

function wp_get_theme_preview_path( $current_stylesheet = null ) {
	if ( ! current_user_can( 'switch_themes' ) ) {
		return $current_stylesheet;
	}

	$preview_stylesheet = ! empty( $_GET['wp_theme_preview'] ) ? sanitize_text_field( wp_unslash( $_GET['wp_theme_preview'] ) ) : null;
	$wp_theme           = wp_get_theme( $preview_stylesheet );
	if ( ! is_wp_error( $wp_theme->errors() ) ) {
		if ( current_filter() === 'template' ) {
			$theme_path = $wp_theme->get_template();
		} else {
			$theme_path = $wp_theme->get_stylesheet();
		}

		return sanitize_text_field( $theme_path );
	}

	return $current_stylesheet;
}

📄 原文内容

Filters the blog option to return the path for the previewed theme.

Parameters

$current_stylesheetstringoptional
The current theme’s stylesheet or template path.

Default:null

Return

string The previewed theme’s stylesheet or template path.

Source

function wp_get_theme_preview_path( $current_stylesheet = null ) {
	if ( ! current_user_can( 'switch_themes' ) ) {
		return $current_stylesheet;
	}

	$preview_stylesheet = ! empty( $_GET['wp_theme_preview'] ) ? sanitize_text_field( wp_unslash( $_GET['wp_theme_preview'] ) ) : null;
	$wp_theme           = wp_get_theme( $preview_stylesheet );
	if ( ! is_wp_error( $wp_theme->errors() ) ) {
		if ( current_filter() === 'template' ) {
			$theme_path = $wp_theme->get_template();
		} else {
			$theme_path = $wp_theme->get_stylesheet();
		}

		return sanitize_text_field( $theme_path );
	}

	return $current_stylesheet;
}

Changelog

Version Description
6.3.0 Introduced.