Alert: This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.

_wp_theme_json_webfonts_handler() WordPress Function

The _wp_theme_json_webfonts_handler() function is used to retrieve webfonts used by a theme. It accepts a theme object as its only parameter and returns an array of fonts.

_wp_theme_json_webfonts_handler() #

Runs the theme.json webfonts handler.


Description

Using WP_Theme_JSON_Resolver, it gets the fonts defined in the theme.json for the current selection and style variations, validates the font-face properties, generates the ‘@font-face’ style declarations, and then enqueues the styles for both the editor and front-end.

Design Notes: This is not a public API, but rather an internal handler. A future public Webfonts API will replace this stopgap code.

This code design is intentional. a. It hides the inner-workings. b. It does not expose API ins or outs for consumption. c. It only works with a theme’s theme.json.

Why? a. To avoid backwards-compatibility issues when the Webfonts API is introduced in Core. b. To make fontFace declarations in theme.json work.


Top ↑

Source

File: wp-includes/script-loader.php

3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
function _wp_theme_json_webfonts_handler() {
    // Block themes are unavailable during installation.
    if ( wp_installing() ) {
        return;
    }
 
    // Webfonts to be processed.
    $registered_webfonts = array();
 
    /**
     * Gets the webfonts from theme.json.
     *
     * @since 6.0.0
     *
     * @return array Array of defined webfonts.
     */
    $fn_get_webfonts_from_theme_json = static function() {
        // Get settings from theme.json.
        $settings = WP_Theme_JSON_Resolver::get_merged_data()->get_settings();
 
        // If in the editor, add webfonts defined in variations.
        if ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
            $variations = WP_Theme_JSON_Resolver::get_style_variations();
            foreach ( $variations as $variation ) {
                // Skip if fontFamilies are not defined in the variation.
                if ( empty( $variation['settings']['typography']['fontFamilies'] ) ) {
                    continue;
                }
 
                // Initialize the array structure.
                if ( empty( $settings['typography'] ) ) {
                    $settings['typography'] = array();
                }
                if ( empty( $settings['typography']['fontFamilies'] ) ) {
                    $settings['typography']['fontFamilies'] = array();
                }
                if ( empty( $settings['typography']['fontFamilies']['theme'] ) ) {
                    $settings['typography']['fontFamilies']['theme'] = array();
                }
 
                // Combine variations with settings. Remove duplicates.
                $settings['typography']['fontFamilies']['theme'] = array_merge( $settings['typography']['fontFamilies']['theme'], $variation['settings']['typography']['fontFamilies']['theme'] );
                $settings['typography']['fontFamilies']          = array_unique( $settings['typography']['fontFamilies'] );
            }
        }
 
        // Bail out early if there are no settings for webfonts.
        if ( empty( $settings['typography']['fontFamilies'] ) ) {
            return array();
        }
 
        $webfonts = array();
 
        // Look for fontFamilies.
        foreach ( $settings['typography']['fontFamilies'] as $font_families ) {
            foreach ( $font_families as $font_family ) {
 
                // Skip if fontFace is not defined.
                if ( empty( $font_family['fontFace'] ) ) {
                    continue;
                }
 
                // Skip if fontFace is not an array of webfonts.
                if ( ! is_array( $font_family['fontFace'] ) ) {
                    continue;
                }
 
                $webfonts = array_merge( $webfonts, $font_family['fontFace'] );
            }
        }
 
        return $webfonts;
    };
 
    /**
     * Transforms each 'src' into an URI by replacing 'file:./'
     * placeholder from theme.json.
     *
     * The absolute path to the webfont file(s) cannot be defined in
     * theme.json. `file:./` is the placeholder which is replaced by
     * the theme's URL path to the theme's root.
     *
     * @since 6.0.0
     *
     * @param array $src Webfont file(s) `src`.
     * @return array Webfont's `src` in URI.
     */
    $fn_transform_src_into_uri = static function( array $src ) {
        foreach ( $src as $key => $url ) {
            // Tweak the URL to be relative to the theme root.
            if ( ! str_starts_with( $url, 'file:./' ) ) {
                continue;
            }
 
            $src[ $key ] = get_theme_file_uri( str_replace( 'file:./', '', $url ) );
        }
 
        return $src;
    };
 
    /**
     * Converts the font-face properties (i.e. keys) into kebab-case.
     *
     * @since 6.0.0
     *
     * @param array $font_face Font face to convert.
     * @return array Font faces with each property in kebab-case format.
     */
    $fn_convert_keys_to_kebab_case = static function( array $font_face ) {
        foreach ( $font_face as $property => $value ) {
            $kebab_case               = _wp_to_kebab_case( $property );
            $font_face[ $kebab_case ] = $value;
            if ( $kebab_case !== $property ) {
                unset( $font_face[ $property ] );
            }
        }
 
        return $font_face;
    };
 
    /**
     * Validates a webfont.
     *
     * @since 6.0.0
     *
     * @param array $webfont The webfont arguments.
     * @return array|false The validated webfont arguments, or false if the webfont is invalid.
     */
    $fn_validate_webfont = static function( $webfont ) {
        $webfont = wp_parse_args(
            $webfont,
            array(
                'font-family'  => '',
                'font-style'   => 'normal',
                'font-weight'  => '400',
                'font-display' => 'fallback',
                'src'          => array(),
            )
        );
 
        // Check the font-family.
        if ( empty( $webfont['font-family'] ) || ! is_string( $webfont['font-family'] ) ) {
            trigger_error( __( 'Webfont font family must be a non-empty string.' ) );
 
            return false;
        }
 
        // Check that the `src` property is defined and a valid type.
        if ( empty( $webfont['src'] ) || ( ! is_string( $webfont['src'] ) && ! is_array( $webfont['src'] ) ) ) {
            trigger_error( __( 'Webfont src must be a non-empty string or an array of strings.' ) );
 
            return false;
        }
 
        // Validate the `src` property.
        foreach ( (array) $webfont['src'] as $src ) {
            if ( ! is_string( $src ) || '' === trim( $src ) ) {
                trigger_error( __( 'Each webfont src must be a non-empty string.' ) );
 
                return false;
            }
        }
 
        // Check the font-weight.
        if ( ! is_string( $webfont['font-weight'] ) && ! is_int( $webfont['font-weight'] ) ) {
            trigger_error( __( 'Webfont font weight must be a properly formatted string or integer.' ) );
 
            return false;
        }
 
        // Check the font-display.
        if ( ! in_array( $webfont['font-display'], array( 'auto', 'block', 'fallback', 'swap' ), true ) ) {
            $webfont['font-display'] = 'fallback';
        }
 
        $valid_props = array(
            'ascend-override',
            'descend-override',
            'font-display',
            'font-family',
            'font-stretch',
            'font-style',
            'font-weight',
            'font-variant',
            'font-feature-settings',
            'font-variation-settings',
            'line-gap-override',
            'size-adjust',
            'src',
            'unicode-range',
        );
 
        foreach ( $webfont as $prop => $value ) {
            if ( ! in_array( $prop, $valid_props, true ) ) {
                unset( $webfont[ $prop ] );
            }
        }
 
        return $webfont;
    };
 
    /**
     * Registers webfonts declared in theme.json.
     *
     * @since 6.0.0
     *
     * @uses $registered_webfonts To access and update the registered webfonts registry (passed by reference).
     * @uses $fn_get_webfonts_from_theme_json To run the function that gets the webfonts from theme.json.
     * @uses $fn_convert_keys_to_kebab_case To run the function that converts keys into kebab-case.
     * @uses $fn_validate_webfont To run the function that validates each font-face (webfont) from theme.json.
     */
    $fn_register_webfonts = static function() use ( &$registered_webfonts, $fn_get_webfonts_from_theme_json, $fn_convert_keys_to_kebab_case, $fn_validate_webfont, $fn_transform_src_into_uri ) {
        $registered_webfonts = array();
 
        foreach ( $fn_get_webfonts_from_theme_json() as $webfont ) {
            if ( ! is_array( $webfont ) ) {
                continue;
            }
 
            $webfont = $fn_convert_keys_to_kebab_case( $webfont );
 
            $webfont = $fn_validate_webfont( $webfont );
 
            $webfont['src'] = $fn_transform_src_into_uri( (array) $webfont['src'] );
 
            // Skip if not valid.
            if ( empty( $webfont ) ) {
                continue;
            }
 
            $registered_webfonts[] = $webfont;
        }
    };
 
    /**
     * Orders 'src' items to optimize for browser support.
     *
     * @since 6.0.0
     *
     * @param array $webfont Webfont to process.
     * @return array Ordered `src` items.
     */
    $fn_order_src = static function( array $webfont ) {
        $src         = array();
        $src_ordered = array();
 
        foreach ( $webfont['src'] as $url ) {
            // Add data URIs first.
            if ( str_starts_with( trim( $url ), 'data:' ) ) {
                $src_ordered[] = array(
                    'url'    => $url,
                    'format' => 'data',
                );
                continue;
            }
            $format         = pathinfo( $url, PATHINFO_EXTENSION );
            $src[ $format ] = $url;
        }
 
        // Add woff2.
        if ( ! empty( $src['woff2'] ) ) {
            $src_ordered[] = array(
                'url'    => sanitize_url( $src['woff2'] ),
                'format' => 'woff2',
            );
        }
 
        // Add woff.
        if ( ! empty( $src['woff'] ) ) {
            $src_ordered[] = array(
                'url'    => sanitize_url( $src['woff'] ),
                'format' => 'woff',
            );
        }
 
        // Add ttf.
        if ( ! empty( $src['ttf'] ) ) {
            $src_ordered[] = array(
                'url'    => sanitize_url( $src['ttf'] ),
                'format' => 'truetype',
            );
        }
 
        // Add eot.
        if ( ! empty( $src['eot'] ) ) {
            $src_ordered[] = array(
                'url'    => sanitize_url( $src['eot'] ),
                'format' => 'embedded-opentype',
            );
        }
 
        // Add otf.
        if ( ! empty( $src['otf'] ) ) {
            $src_ordered[] = array(
                'url'    => sanitize_url( $src['otf'] ),
                'format' => 'opentype',
            );
        }
        $webfont['src'] = $src_ordered;
 
        return $webfont;
    };
 
    /**
     * Compiles the 'src' into valid CSS.
     *
     * @since 6.0.0
     *
     * @param string $font_family Font family.
     * @param array  $value       Value to process.
     * @return string The CSS.
     */
    $fn_compile_src = static function( $font_family, array $value ) {
        $src = "local($font_family)";
 
        foreach ( $value as $item ) {
 
            if (
                str_starts_with( $item['url'], site_url() ) ||
                str_starts_with( $item['url'], home_url() )
            ) {
                $item['url'] = wp_make_link_relative( $item['url'] );
            }
 
            $src .= ( 'data' === $item['format'] )
                ? ", url({$item['url']})"
                : ", url('{$item['url']}') format('{$item['format']}')";
        }
 
        return $src;
    };
 
    /**
     * Compiles the font variation settings.
     *
     * @since 6.0.0
     *
     * @param array $font_variation_settings Array of font variation settings.
     * @return string The CSS.
     */
    $fn_compile_variations = static function( array $font_variation_settings ) {
        $variations = '';
 
        foreach ( $font_variation_settings as $key => $value ) {
            $variations .= "$key $value";
        }
 
        return $variations;
    };
 
    /**
     * Builds the font-family's CSS.
     *
     * @since 6.0.0
     *
     * @uses $fn_compile_src To run the function that compiles the src.
     * @uses $fn_compile_variations To run the function that compiles the variations.
     *
     * @param array $webfont Webfont to process.
     * @return string This font-family's CSS.
     */
    $fn_build_font_face_css = static function( array $webfont ) use ( $fn_compile_src, $fn_compile_variations ) {
        $css = '';
 
        // Wrap font-family in quotes if it contains spaces.
        if (
            str_contains( $webfont['font-family'], ' ' ) &&
            ! str_contains( $webfont['font-family'], '"' ) &&
            ! str_contains( $webfont['font-family'], "'" )
        ) {
            $webfont['font-family'] = '"' . $webfont['font-family'] . '"';
        }
 
        foreach ( $webfont as $key => $value ) {
            /*
             * Skip "provider", since it's for internal API use,
             * and not a valid CSS property.
             */
            if ( 'provider' === $key ) {
                continue;
            }
 
            // Compile the "src" parameter.
            if ( 'src' === $key ) {
                $value = $fn_compile_src( $webfont['font-family'], $value );
            }
 
            // If font-variation-settings is an array, convert it to a string.
            if ( 'font-variation-settings' === $key && is_array( $value ) ) {
                $value = $fn_compile_variations( $value );
            }
 
            if ( ! empty( $value ) ) {
                $css .= "$key:$value;";
            }
        }
 
        return $css;
    };
 
    /**
     * Gets the '@font-face' CSS styles for locally-hosted font files.
     *
     * @since 6.0.0
     *
     * @uses $registered_webfonts To access and update the registered webfonts registry (passed by reference).
     * @uses $fn_order_src To run the function that orders the src.
     * @uses $fn_build_font_face_css To run the function that builds the font-face CSS.
     *
     * @return string The `@font-face` CSS.
     */
    $fn_get_css = static function() use ( &$registered_webfonts, $fn_order_src, $fn_build_font_face_css ) {
        $css = '';
 
        foreach ( $registered_webfonts as $webfont ) {
            // Order the webfont's `src` items to optimize for browser support.
            $webfont = $fn_order_src( $webfont );
 
            // Build the @font-face CSS for this webfont.
            $css .= '@font-face{' . $fn_build_font_face_css( $webfont ) . '}';
        }
 
        return $css;
    };
 
    /**
     * Generates and enqueues webfonts styles.
     *
     * @since 6.0.0
     *
     * @uses $fn_get_css To run the function that gets the CSS.
     */
    $fn_generate_and_enqueue_styles = static function() use ( $fn_get_css ) {
        // Generate the styles.
        $styles = $fn_get_css();
 
        // Bail out if there are no styles to enqueue.
        if ( '' === $styles ) {
            return;
        }
 
        // Enqueue the stylesheet.
        wp_register_style( 'wp-webfonts', '' );
        wp_enqueue_style( 'wp-webfonts' );
 
        // Add the styles to the stylesheet.
        wp_add_inline_style( 'wp-webfonts', $styles );
    };
 
    /**
     * Generates and enqueues editor styles.
     *
     * @since 6.0.0
     *
     * @uses $fn_get_css To run the function that gets the CSS.
     */
    $fn_generate_and_enqueue_editor_styles = static function() use ( $fn_get_css ) {
        // Generate the styles.
        $styles = $fn_get_css();
 
        // Bail out if there are no styles to enqueue.
        if ( '' === $styles ) {
            return;
        }
 
        wp_add_inline_style( 'wp-block-library', $styles );
    };
 
    add_action( 'wp_loaded', $fn_register_webfonts );
    add_action( 'wp_enqueue_scripts', $fn_generate_and_enqueue_styles );
    add_action( 'admin_init', $fn_generate_and_enqueue_editor_styles );
}


Top ↑

Changelog

Changelog
VersionDescription
6.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by the Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.