Skip to content

Add Theme.json font families to Astra custom fonts #65

Description

@xoex

Hi. I'm using Astra and Custom fonts plugin. Inside my child theme, I added a theme.json file and added some typographies.
like this :

{
  "version": 2,
  "settings": {
    "typography": {
        {
          "fontFamily": "CustomFont",
          "name": "CustomFont",
          "slug": "custom-font",
          "fontFace": [
            {
              "fontFamily": "CustomFont",
              "fontWeight": "100",
              "fontStyle": "normal",
              "fontStretch": "normal",
              "src": [
                "file:./assets/fonts/somefolder/customfont.woff"
              ]
            },
.....

But astra doesn't automatically detect theme.json font families (at least for me), I wrote this code and i'm using it in child theme,
I think you can add this to astra theme or custom fonts plugin (as a setting, like to check to tickbox and theme.json font families will be added to astra custom fonts).

<?php

class AddThemeJsonFontsToAstra
{
    public static $instance;

    private $fonts;
    public function __construct()
    {
        $this->fonts = [];
        add_action('init', array($this, 'init'));
        add_filter('astra_system_fonts', array($this, 'add_custom_fonts'));

    }

    public function init()
    {
        $fonts = wp_get_global_settings(['typography', 'fontFamilies', 'theme']);
        if (!empty($fonts)) {
            foreach ($fonts as $font) {
                if (isset($font['fontFamily']) && isset($font['fontFace']) && is_array($font['fontFace'])) {
                    $weights = array_column($font['fontFace'], 'fontWeight');
                    $this->fonts[$font['fontFamily']] = ['weights' => $weights];
                }
            }
        }

    }

    public function add_custom_fonts($fonts)
    {
        foreach($this->fonts as $fontFamily => $fontData)
        {
            if (!isset($fonts[$fontFamily])) {
                $fonts[$fontFamily] = $fontData;
            }
        }
        return $fonts;
    }
}

AddThemeJsonFontsToAstra::$instance = new AddThemeJsonFontsToAstra();

Of course code should be optimized, 1. fontfamily should be get from fontFace section, 2. fontWeight can be a range like "200 900". this code can't add them.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions