函数文档

wp_get_custom_css()

💡 云策文档标注

概述

wp_get_custom_css() 函数用于获取已保存的自定义 CSS 内容以供渲染。它接受一个可选的样式表名称参数,并返回对应的 CSS 字符串。

关键要点

  • 函数参数 $stylesheet 为可选字符串,指定主题样式表名称,默认为当前活动主题。
  • 返回值为字符串,即自定义 CSS 文章的内容。
  • 内部通过 wp_get_custom_css_post() 获取自定义 CSS 文章对象,并提取其 post_content。
  • 使用 apply_filters('wp_get_custom_css', $css, $stylesheet) 钩子允许过滤 CSS 输出。

代码示例

function wp_get_custom_css( $stylesheet = '' ) {
    $css = '';

    if ( empty( $stylesheet ) ) {
        $stylesheet = get_stylesheet();
    }

    $post = wp_get_custom_css_post( $stylesheet );
    if ( $post ) {
        $css = $post->post_content;
    }

    $css = apply_filters( 'wp_get_custom_css', $css, $stylesheet );

    return $css;
}

注意事项

  • 函数自 WordPress 4.7.0 版本引入。
  • 相关函数包括 wp_get_custom_css_post()、get_stylesheet() 和 apply_filters()。
  • 常用于 wp_enqueue_global_styles_custom_css()、wp_enqueue_global_styles() 和 wp_custom_css_cb() 等函数中。

📄 原文内容

Fetches the saved Custom CSS content for rendering.

Parameters

$stylesheetstringoptional
A theme object stylesheet name. Defaults to the active theme.

Return

string The Custom CSS Post content.

Source

function wp_get_custom_css( $stylesheet = '' ) {
	$css = '';

	if ( empty( $stylesheet ) ) {
		$stylesheet = get_stylesheet();
	}

	$post = wp_get_custom_css_post( $stylesheet );
	if ( $post ) {
		$css = $post->post_content;
	}

	/**
	 * Filters the custom CSS output into the head element.
	 *
	 * @since 4.7.0
	 *
	 * @param string $css        CSS pulled in from the Custom CSS post type.
	 * @param string $stylesheet The theme stylesheet name.
	 */
	$css = apply_filters( 'wp_get_custom_css', $css, $stylesheet );

	return $css;
}

Hooks

apply_filters( ‘wp_get_custom_css’, string $css, string $stylesheet )

Filters the custom CSS output into the head element.

Changelog

Version Description
4.7.0 Introduced.