Skip to content

Commit

Permalink
Filter actually used fonts from all registered providers when renderi…
Browse files Browse the repository at this point in the history
…ng the page
  • Loading branch information
zaguiini committed Feb 28, 2022
1 parent 48cd12a commit 64c912f
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions lib/compat/wordpress-6.0/class-wp-webfonts.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ class WP_Webfonts {
*/
private static $webfonts = array();

/**
* An array of actually used webfonts by the front-end.
*
* @static
* @access private
* @var array
*/
private static $used_webfonts = array();

/**
* The name of the webfont cache option name.
*
Expand Down Expand Up @@ -61,6 +70,8 @@ public function init() {
$hook = 'wp_enqueue_scripts';
}

add_action( 'init', array( $this, 'load_used_webfonts_for_current_template' ) );

add_action( 'save_post_wp_template', array( $this, 'save_used_webfonts_for_template' ), 10, 2 );
add_action( 'save_post_wp_template_part', array( $this, 'update_webfonts_used_by_templates' ), 10, 2 );

Expand All @@ -70,6 +81,27 @@ public function init() {
add_action( 'admin_init', array( $this, 'generate_and_enqueue_editor_styles' ) );
}

/**
* Set list of used fonts in the current page.
*
* @return void
*/
public function load_used_webfonts_for_current_template() {
$used_webfonts = get_option( self::$webfont_cache_option, array() );

foreach ( $used_webfonts as $template => $webfonts ) {
add_filter(
$template . '_template',
function() use ( $webfonts ) {
self::$used_webfonts = array_merge(
self::$used_webfonts,
$webfonts
);
}
);
}
}

/**
* Updates the fonts used by the templates.
* We need to do that because there's no indication on which templates uses which template parts,
Expand Down Expand Up @@ -280,10 +312,31 @@ public function register_provider( $provider, $class ) {
return true;
}

/**
* Filter unused webfonts based off self::$used_webfonts.
*
* @return void
*/
private function filter_unused_webfonts_from_providers() {
$registered_webfonts = $this->get_fonts();

foreach ( $registered_webfonts as $id => $webfont ) {
$font_name = _wp_to_kebab_case( $webfont['font-family'] );

if ( ! isset( self::$used_webfonts[ $font_name ] ) ) {
unset( $registered_webfonts[ $id ] );
}
}

self::$webfonts = $registered_webfonts;
}

/**
* Generate and enqueue webfonts styles.
*/
public function generate_and_enqueue_styles() {
$this->filter_unused_webfonts_from_providers();

// Generate the styles.
$styles = $this->generate_styles();

Expand Down

0 comments on commit 64c912f

Please sign in to comment.