Search by

mickey-kay / better-font-awesome-library

McGuive7

Better Font Awesome Library for WordPress

Package info

github.com/MickeyKay/better-font-awesome-library

pkg:composer/mickey-kay/better-font-awesome-library

Statistics

Installs: 2 918

Dependents: 1

Suggesters: 0

Stars: 36

Open Issues: 12


README

The easiest way to integrate Font Awesome into your WordPress project.

Table of contents

  1. Introduction
  2. Features
  3. Installation
  4. Stable release and rollback
  5. Font Awesome 7 and BFAL 3
  6. Changelog
  7. Usage
  8. Local asset delivery
  9. Metadata lifecycle
  10. Compatibility notes
  11. Initialization Parameters
  12. Shortcode
  13. The Better Font Awesome Library Object
  14. Filters
  15. To Do
  16. Credits

Introduction

The Better Font Awesome Library integrates validated Font Awesome Free metadata and channel-coupled assets into WordPress projects, along with CSS registration, a shortcode, and a TinyMCE icon shortcode generator. Consumers can supply locally resolved metadata and schedule asynchronous refresh work without making normal requests wait on the Font Awesome service. Tagged BFAL 2.x releases use Font Awesome 5.x; BFAL 3 defaults to Font Awesome 7.x.

Features

  • Returns validated local metadata immediately from a provider, transient, or bundled fallback.
  • Exposes an explicit, bounded refresh operation for consumer-controlled asynchronous workers.
  • Generates an easy-to-use PHP object that contains all relevant info for the version of Font Awesome you're using, including: version, stylesheet URL, array of available icons, and prefix used (icon or fa).
  • Offers optional bundled-local asset delivery for the packaged Font Awesome Free 7 catalog, CSS, and fonts.
  • Loads the exact assets coupled to the immutable selected Font Awesome Free channel.
  • Includes a TinyMCE drop-down shortcode generator.
  • Includes validated Font Awesome Free 7.3.1 CSS, WOFF2, and metadata as the immediate default fallback, plus the established Font Awesome Free 5.14.0 metadata fallback for explicit 5.x consumers. The bfa_fallback_release_data_path filter remains available for the 5.x fallback.
  • Preserves the established bfa-release-data transient for backward compatibility.

Installation

The Better Font Awesome Library should ideally be installed via Composer:

composer require mickey-kay/better-font-awesome-library:"^3.1"

Alternately, you can install the library manually, which can be useful for development and/or custom builds:

git clone https://github.com/MickeyKay/better-font-awesome-library.git
cd better-font-awesome-library
npm run build

Stable release and rollback

Composer users can select the stable BFAL 3 line with optional local delivery after its tag is published:

composer require mickey-kay/better-font-awesome-library:"^3.1"

BFAL 3 defaults to Font Awesome 7 and preserves explicit Font Awesome 5 selection. Automatic delivery remains the default, with validated provider or transient metadata taking precedence over the bundled fallback. Ordinary requests perform no metadata or candidate-validation HTTP. BFAL provides validated local metadata, packaged fallback assets, and explicit asynchronous refresh operations while consumers continue to own WordPress persistence, scheduling, locking, retry, freshness, and migration policy.

Optional bundled-local delivery pins the active FA7 Free catalog, CSS, compatibility styles, and fonts to the same packaged release, with no remote refresh. New icons arrive through library or embedding-plugin updates. The first caller owns the mode and channel; explicit FA5 with local delivery fails closed without switching channels.

To roll back to the Font Awesome 5 stable line, restore BFAL 2.1.0 and redeploy the resulting lockfile:

composer require mickey-kay/better-font-awesome-library:2.1.0 --with-all-dependencies

BFAL follows versions published from repository tags. See CHANGELOG.md for release history. WordPress stylesheet and script cache keys use the installed BFAL version.

Font Awesome 7 and BFAL 3

BFAL 3.0.0 changes the default Font Awesome major. Existing tagged BFAL 2.x releases remain the Font Awesome 5-compatible stable line for consumers that cannot yet adopt the new default.

BFAL 3 defaults to the 7.x release channel when the first caller supplies no release_channel argument. Explicit release_channel => '7.x' is identical to that default. Consumers that deliberately require the legacy runtime can select release_channel => '5.x'. The first caller owns this immutable selection, just like every other initialization argument.

The 7.x channel validates and loads the packaged Font Awesome Free 7.3.1 baseline immediately. Its CSS and WOFF2 URLs are derived from the BFAL installation URL, so activation needs no HTTP request, cron run, migration, pending state, or setting. Normal frontend, admin, editor, REST, shortcode, picker, and getter paths perform no metadata HTTP.

In automatic mode, an explicit 7.x background refresh discovers only the latest supported 7.x Free release. A same-version check uses one Font Awesome metadata request. A genuinely newer candidate is limited to 18 total requests, 4 MiB of response bodies, and 30 seconds. It must pass exact npm publication, cdnjs and jsDelivr byte comparison, CSS SRI, required WOFF2, CSS-to-font reference, family, style, icon, and alias validation. The worker returns one complete schema-2 record or a sanitized WP_Error; BFAL does not persist 7.x refresh results. Consumer code owns last-known-good storage, scheduling, locking, retry, and freshness policy.

The 7.x channel never crosses automatically to Font Awesome 8. Supporting another Font Awesome major requires a separately reviewed BFAL compatibility release.

Usage

  1. Copy the /better-font-awesome-library folder into your project.

  2. Add the following code to your main plugin file or your theme's functions.php file.

add_action( 'init', 'my_prefix_load_bfa' );
    /**
    * Initialize the Better Font Awesome Library.
    *
    * (see usage notes below on proper hook priority)
    */
    function my_prefix_load_bfa() {

    // Include the main library file. Make sure to modify the path to match your directory structure.
    require_once ( dirname( __FILE__ ) . '/better-font-awesome-library/better-font-awesome-library.php' );

    // Set the library initialization args (defaults shown).
    $args = array(
      'include_v4_shim'     => false,
      'remove_existing_fa'  => false,
      'load_styles'         => true,
      'load_admin_styles'   => true,
      'load_shortcode'      => true,
      'load_tinymce_plugin' => true,
      'release_data_provider' => null,
      'release_data_refresh_callback' => null,
      'release_channel' => '7.x',
      'asset_delivery' => 'automatic',
    );

    // Initialize the Better Font Awesome Library.
    Better_Font_Awesome_Library::get_instance( $args );
}
  1. If desired, use the Better Font Awesome Library object to manually include Font Awesome CSS, output lists of available icons, create your own shortcodes, and much more.

Usage Notes

The Better Font Awesome Library is designed to work in conjunction with the Better Font Awesome WordPress plugin. The plugin initializes this library (with its own initialization args) on the init hook, priority 5. When using the Better Font Awesome Library in your project, you have two options:

  1. Initialize later so Better Font Awesome reaches the singleton first. Your later arguments are ignored, and Better Font Awesome owns the configuration. This is the default behavior shown above by initializing on the init hook at priority 10.
  2. Initialize earlier to take ownership. Better Font Awesome's later arguments are ignored and cannot override yours.

This first-caller contract is intentional and applies to every initialization argument, including asset delivery mode, release channel, release-data provider, and refresh callback. Hook priority determines ownership. BFAL does not provide post-construction registration, reset, mutation, or ownership transfer.

Local asset delivery

The optional asset_delivery initialization argument accepts exactly two string values:

  • automatic (default) preserves existing behavior for both 7.x and explicit 5.x. Validated provider or transient metadata takes precedence over the bundled fallback. Accepted releases use their matching CDN assets; the FA7 bundled fallback uses packaged assets. Consumer-managed background refresh can discover newer releases within the selected channel.
  • bundled-local selects only the packaged Font Awesome Free 7 release. The active version, icon catalog, picker data, CSS, compatibility styles, and WOFF2 fonts all come from that bundle immediately. New Font Awesome releases arrive through BFAL updates, or through updates to a plugin that packages BFAL. Provider data and legacy transients are neither read nor mutated, even if they contain a matching or newer release.
$library = Better_Font_Awesome_Library::get_instance( array(
    'asset_delivery' => 'bundled-local',
    'release_channel' => '7.x',
) );

// Use the effective first caller's mode when deciding whether to schedule work.
if ( 'automatic' === $library->get_asset_delivery() ) {
    // Apply your integration's scheduling and freshness policy.
}

The first get_instance() caller owns the mode and channel after the existing initialization filters run. Later callers and later filter changes cannot change that selection. Hook priority is the ownership mechanism; an earlier consumer can intentionally prevent Better Font Awesome from owning BFAL. Integrations must inspect get_asset_delivery() instead of inferring mode from URLs or record provenance. The packaged record retains its existing source => 'fallback' provenance in both modes.

Local delivery supports FA7 Free only. Explicit release_channel => '5.x' with bundled-local fails closed with get_error( 'delivery' ) code bfa_asset_delivery_channel_unsupported, no remote requests, and no channel switch. An unsupported mode fails closed with bfa_asset_delivery_unsupported. In either case BFAL exposes no active release, icons, or stylesheet URLs. Fix initialization for a subsequent request; a later caller cannot repair the established instance.

In local mode, request_release_data_refresh() is a no-op: neither the callback nor the refresh action runs. refresh_release_data() returns a WP_Error with code bfa_refresh_disabled, performs zero HTTP or persistence, and leaves the active record unchanged. This is an intentional disabled operation, not a retryable refresh failure, and it does not add an admin diagnostic. Integrations should skip scheduling and retries in local mode and preserve their existing remote metadata for a future automatic-mode request. Invalid initialization instead returns its configuration error from explicit refresh.

If bundled metadata cannot be read or validated, or a required CSS/font file is missing, unreadable, or empty at initialization, BFAL reports a fallback error and exposes no active catalog or stylesheet URLs. Missing assets use error code bfa_bundled_asset_unavailable; metadata errors retain the existing validator codes. Restore a complete BFAL package to recover. A browser delivery failure leaves the affected icons unavailable. BFAL never substitutes third-party assets or requests refresh work in local mode.

Stylesheet handles, loading flags, editor integration, and existing integrity/CORS handling remain unchanged. FA5 compatibility font faces are included for legacy markup rendered with FA7; this does not add FA5 asset self-hosting. Optional v4 styles still follow include_v4_shim. CSS font references stay inside the bundled asset tree and URLs use the BFAL installation URL. Sites that rewrite installation URLs through a CDN must account for that infrastructure separately. This feature controls BFAL's Font Awesome asset delivery only, not requests made by other plugins, themes, or site infrastructure.

Metadata lifecycle

Normal frontend, admin, editor, REST, and cron-triggering requests never call the Font Awesome metadata service synchronously. In automatic mode, BFAL resolves release data only for the immutable channel selected during first-caller initialization, in this order:

  1. The per-request validated value.
  2. An optional release_data_provider callable that returns already-resolved local data.
  3. A validated value from the established bfa-release-data transient.
  4. The validated bundled fallback for the selected channel: Font Awesome Free 7.3.1 for 7.x, or the established Font Awesome Free 5.14.0 fallback for explicit 5.x.

When automatic mode reaches the fallback, it invokes release_data_refresh_callback once if configured. Otherwise it fires bfa_release_data_refresh_requested with the supported channel and library instance. The handler must only schedule work and return promptly. Scheduling, locking, durable last-known-good persistence, retry backoff, jitter, and freshness policy belong to the consumer.

A provider may return a release array or a declared BFAL release record. An exact empty array means that the provider has no locally available candidate yet. Declared records must use the exact supported schema_version, channel, and edition, an allowed source, and a fully valid nested release. BFAL rejects mismatches rather than discarding or normalizing them.

In automatic mode, an asynchronous worker can call refresh_release_data(). For explicit 5.x, the established operation retains its existing validated transient behavior and release-array return value. For 7.x, one bounded attempt returns a complete validated schema-2 record or a sanitized WP_Error and performs no BFAL persistence. Both paths require TLS, reject redirects and unsafe URLs, and leave the prior validated data untouched on failure.

The Font Awesome API and CDN are external services. Consumers should document when they contact those services and apply the consent, privacy, scheduling, and persistence policy appropriate to their application.

Compatibility notes

Better_Font_Awesome_Library::get_instance( $args ) retains its established first-call contract. The first caller owns initialization, and arguments passed to later calls are ignored. An earlier plugin or theme can therefore intentionally own BFAL before Better Font Awesome initializes. Better Font Awesome is not guaranteed to override that owner.

This precedence is supported compatibility behavior. BFAL remains safe when another consumer owns it: normal metadata resolution performs no synchronous HTTP, release data is validated before adoption, and validated transient or bundled fallback data remains available. A new public ownership API would require a demonstrated interoperability need and explicit repository owner approval.

Initialization Parameters ($args)

The following arguments can be used to initialize the library using Better_Font_Awesome_Library::get_instance( $args ):

$args['include_v4_shim']

(boolean) Include the Font Awesome v4 shim CSS stylesheet to support legacy icon.

  • true
  • false (default)

$args['remove_existing_fa']

(boolean) Attempts to remove existing Font Awesome styles and shortcodes. This can be useful to prevent conflicts with other themes/plugins, but is no guarantee.

  • true
  • false (default)

$args['load_styles']

(boolean) Automatically loads Font Awesome CSS on the front-end of your site using wp_enqueue_scripts().

  • true (default)
  • false - use this if you don't want to load the Font Awesome CSS on the front-end, or wish to do it yourself.

$args['load_admin_styles']

(boolean) Automatically loads Font Awesome CSS on the admin of your site using admin_enqueue_scripts().

  • true (default)
  • false - use this if you don't want to load the Font Awesome CSS in the admin, or wish to do it yourself.

$args['load_shortcode']

(boolean) Loads the included [icon] shortcode.

  • true (default)
  • false

load_tinymce_plugin

(boolean) Loads a TinyMCE drop-down list of available icons (based on the active Font Awesome version), which generates an [icon] shortcode.

  • true (default)
  • false

$args['asset_delivery']

(string) Immutable delivery mode: automatic (default) or bundled-local. Local delivery is FA7-only and pins the catalog and all Font Awesome assets to the packaged release. See local asset delivery for update, ownership, refresh, and failure behavior.

$args['release_data_provider']

(callable|null) Optional callable that returns an already-resolved release array or BFAL release record. An exact empty array indicates that no local candidate is currently available. Providers used by normal getters must not perform remote I/O.

$args['release_data_refresh_callback']

(callable|null) Optional callback invoked once when BFAL falls back to bundled data. It receives the supported channel and BFAL instance and must schedule asynchronous work rather than perform transport inline.

$args['release_channel']

(string) Immutable Font Awesome Free major channel selected by the first singleton caller.

  • 7.x (default in BFAL 3)
  • 5.x - explicit legacy behavior compatible with the BFAL 2.x runtime

The selected 7.x channel follows completely validated 7.x releases only. It will not update across a future Font Awesome major.

An unsupported first-caller channel value fails closed. BFAL records a sanitized bfa_channel_unsupported error and returns no release metadata or stylesheet URLs. Because first-caller ownership remains immutable, a later caller cannot replace that invalid selection.

These metadata collaborators are initialization arguments and therefore follow the same first-caller ownership contract. They cannot be added or replaced through a later get_instance() call.

Deprecated

$args['version'] (2.0.0)

The library no longer selects a version through this argument. Validated Font Awesome Free metadata comes from the configured local provider, compatibility transient, or bundled fallback for the immutable selected channel.

(string) Retained for compatibility. Supplied values are ignored because the validated release record selects the supported version within the immutable major channel and its coupled assets.

$args['minified'] (2.0.0)

The library now always defaults to minified CSS.

(boolean) Use minified Font Awesome CSS.

  • true (default) - uses minifed CSS.
  • false - uses unminified CSS.

Shortcode

If either the $args['load_shortcode'] or $args['load_tinymce_plugin'] initialization arg is set to true, then the Better Font Awesome Library will include an [icon] shortcode that can be used as follows:

[icon name="star" class="2x spin" unprefixed_class="my-custom-class"]

name

The unprefixed icon name (e.g. star). The version-specific prefix will be automatically prepended.

class

Unprefixed Font Awesome icon classes. The version-specific prefix will be automatically prepended to each class.

unprefixed_class

Any additional classes that you wish to remain unprefixed (e.g. my-custom-class).

style

The specific icon style (e.g. brand vs. solid) to use.

Shortcode Output

The following shortcode:

[icon name="moon" style="solid" class="2x spin" unprefixed_class="my-custom-class"]

. . . will produce the following HTML:

<i class="fas fa-moon fa-2x fa-spin my-custom-class "></i>

The Better Font Awesome Library Object

The Better Font Awesome Library object can be accessed with the following code: Better_Font_Awesome_Library::get_instance();

The object has the following public methods:

get_version()

(string) Returns the active version of Font Awesome being used.

get_stylesheet_url()

(string) Returns the Font Awesome stylesheet URL.

get_stylesheet_url_v4_shim()

(string) Returns the Font Awesome v4 shim stylesheet URL.

get_icons()

(array) Returns an associative array of icon hex values (index, e.g. \f000) and unprefixed icon names (values, e.g. rocket) for all available icons in the active Font Awesome version.

get_release_icons()

(array) Returns icon data in BFAL's established public icon shape. Schema-2 family and style metadata is adapted without changing that shape.

get_release_assets()

(array) Returns validated Free release asset data for the selected Font Awesome version.

get_release_record()

(array) Returns the validated internal record with schema_version, channel, edition, source, and the compatibility-preserving release array.

get_release_channel()

(string) Returns the immutable selected Font Awesome channel, 7.x by default or explicit 5.x. Returns an empty string when an unsupported first-caller value has caused the runtime to fail closed.

get_asset_delivery()

(string) Returns the immutable first-caller mode, automatic or bundled-local. Returns an empty string when the mode, channel, or mode/channel combination is unsupported; inspect get_errors() for configuration failures. The internal selection remains immutable. A missing or invalid bundle does not invalidate the configuration, so the accessor still returns bundled-local in that case.

request_release_data_refresh()

Requests asynchronous refresh scheduling through the configured callback or bfa_release_data_refresh_requested action. This method performs no remote transport. It does nothing in bundled-local mode or after invalid mode/channel initialization.

refresh_release_data()

(array|WP_Error) In automatic mode, performs one bounded refresh attempt in an explicit worker context. Consumers own locking, retry, and durable persistence policy. Bundled-local mode returns WP_Error( 'bfa_refresh_disabled', ... ) without HTTP, mutation, or an admin diagnostic; do not retry this disabled operation. Invalid initialization returns its configuration error.

get_prefix()

(string) Returns the version-dependent prefix ('fa' or 'icon') that is used in the icons' CSS classes.

get_errors()

(array) Returns sanitized metadata, provider, cache, and fallback errors.

Deprecated

get_api_data() (2.0.0)

This deprecated method is no longer used for ordinary release discovery. The explicit Font Awesome 7 refresh worker uses exact-version jsDelivr files only for mandatory cross-provider byte validation.

(object) Returns version data for the remote jsDelivr CDN (uses jsDelivr API). Includes all available versions and latest version.

Example:

// Initialize the library with custom args.
Better_Font_Awesome_Library::get_instance( $args );

// Get the active Better Font Awesome Library Object.
$my_bfa = Better_Font_Awesome_Library::get_instance();

// Get info on the Better Font Awesome Library object.
$version = $my_bfa->get_version();
$stylesheet_url = $my_bfa->get_stylesheet_url();
$prefix = $my_bfa->get_prefix();
$icons = $my_bfa->get_icons();

// Output all available icons.
foreach ( $icons as $icon ) {
    echo $icon . '<br />';
}

Filters

The Better Font Awesome Library applies the following filters:

bfa_init_args

Applied to the initialization arguments after they have been parsed with default args, but before they are used to fetch any Font Awesome data.

Parameters

  • $init_args (array)

bfa_wp_remote_get_args

Applied to arguments passed to the explicit metadata refresh request. TLS verification, blocking worker transport, no redirects, the maximum timeout, and the maximum response size remain enforced after this filter.

Parameters

  • $wp_remote_get_args (array)

bfa_font_awesome_release_channel

Applied once while the first singleton caller's release channel is initialized. BFAL accepts only 5.x and 7.x. The resolved value is immutable for the lifetime of that instance, so later calls and later filter changes cannot switch metadata or assets. An unsupported result fails closed with no release metadata or stylesheet URLs.

Parameters

  • $channel (string)

bfa_fallback_release_data_path

Applied to the path for the fallback release data JSON file. Can be used to specify an alternate fallback data file.

Parameters

  • $fallback_release_data_path (string)

bfa_release_data_transient_expiration

This value controls how often the plugin will check for the latest updated version of Font Awesome. Can be used to increase/decrease the frequency of this check as desired.

Parameters

  • $api_expiration (int) (default: DAY_IN_SECONDS)

bfa_icon_list

Applied to the icon array after it has been generated from the Font Awesome stylesheet, and before it is assigned to the Better Font Awesome Library object's $icons property.

Parameters

  • $icons (array)

bfa_icon_array

Applied to the normalized icon array after the deprecated bfa_icon_list filter.

Parameters

  • $icons (array)

bfa_icon_class

Applied to the classes that are output on each icon's <i> element.

Parameters

  • $class (string)

bfa_icon_tag

Applied to the tag that is output for each icon. Defaults is 'i', which outputs <i>.

Parameters

  • $tag (string)

bfa_icon

Applied to the entire <i> element that is output for each icon.

Parameters

  • $output (string)

bfa_show_errors

Applied to the boolean that determines whether or not to suppress all Font Awesome warnings that normally display in the admin.

Parameters

  • $show_errors (true)

Actions

bfa_release_data_refresh_requested

In automatic mode, fires once per BFAL request when no valid provider or transient value is available and bundled fallback data is selected. Handlers receive the immutable selected channel (5.x or 7.x) and BFAL instance. Handlers must schedule asynchronous work and return promptly. This action never fires in bundled-local mode.

Deprecated

bfa_fallback_directory_path

This is now replaced by the similar bfa_fallback_release_data_path filter. Applied to the fallback directory path before setting up any fallback CSS info. Can be used to specify an alternate fallback directory to replace the default fallback directory.

The path must be to a local, non-remote, directory.

Parameters

  • $path (string)

bfa_api_transient_expiration (2.0.0)

This data now comes from the GraphQL API. The new bfa_release_data_transient_expiration replaces this legacy filter.

Applied to the API (version information) transient expiration. Can be used to increase/decrease the expiration as desired.

Parameters

  • $api_expiration (int)

bfa_css_transient_expiration (2.0.0)

This data is now no longer necessary.

Applied to the CSS stylesheet data transient expiration. Can be used to increase/decrease the expiration as desired.

Parameters

  • $css_expiration (int)

bfa_force_fallback (2.0.0)

There should no longer be a need to force a fallback.

Applied to the boolean that determines whether or not to force the included fallback version of Font Awesome to load. This can be useful if you're having trouble with delays or timeouts.

Parameters

  • $force_fallback (false)

bfa_prefix (2.0.0)

Given the update to v5+ always, there should be no need to modify the icon prefix.

Applied to the Font Awesome prefix ('fa' or 'icon') before it is assigned to the Better Font Awesome Library object's $prefix property.

Parameters

  • $prefix (string)

To Do

Ideas? File an issue or add a pull request!

  • Add README section on manually updating the fallback version.
  • Remove existing FA? - move to later hook so that it works for styles enqueued via shortcode (= wp_footer basically)

Credits

Special thanks to the following folks and their plugins for inspiration and support:

And many thanks to the following folks who helped with testing and QA: