Skip to content

Instantly share code, notes, and snippets.

@ideag
Created March 16, 2018 09:01
Show Gist options
  • Save ideag/007f3271b1c65d436d56c039d0d8b46c to your computer and use it in GitHub Desktop.
Save ideag/007f3271b1c65d436d56c039d0d8b46c to your computer and use it in GitHub Desktop.
A more elaborate WordPress plugin to add FontAwesome icons via shortcode
<?php
/**
* Plugin Name: FontAwesome
* Version: 0.1.0
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
add_action( 'plugins_loaded', 'FontAwesome' );
function FontAwesome() {
if ( false === FontAwesomeClass::$instance ) {
FontAwesomeClass::$instance = new FontAwesomeClass();
}
return FontAwesomeClass::$instance;
}
class FontAwesomeClass {
public static $instance = false;
public function __construct() {
// Load FontAwesome assets from CDN.
add_action( 'wp_enqueue_scripts', array( $this, 'assets' ) );
// add `defer` attribute to FontAwesome script.
add_filter( 'script_loader_tag', array( $this, 'defer' ), 10, 2 );
// output an icon via [icon] shortcode.
add_shortcode( 'icon', array( $this, 'icon' ) );
}
public function icon( $args = array() ) {
$defaults = array(
'prefix' => 'fas',
'name' => false,
'class' => false,
'size' => false,
'fixed' => false,
'spin' => false,
'pulse' => false,
);
$args = wp_parse_args( $args, $defaults );
$args['class'] = explode( ' ', $args['class'] );
$args['class'][] = $args['prefix'];
$args['class'][] = "fa-{$args['name']}";
if ( false !== $args['size'] ) {
$args['class'][] = "fa-{$args['size']}";
}
if ( false !== $args['fixed'] ) {
$args['class'][] = "fa-fw";
}
if ( false !== $args['spin'] ) {
$args['class'][] = "fa-spin";
}
if ( false !== $args['pulse'] ) {
$args['class'][] = "fa-pulse";
}
$args['class'] = implode( ' ', $args['class'] );
$args['class'] = esc_attr( $args['class'] );
$icon = '<i class="' . $args['class'] . '"></i>';
return $icon;
}
public function defer( $tag, $handle ) {
if ( 'fontawesome' === $handle ) {
$tag = str_replace( ' src', ' defer src', $tag );
}
return $tag;
}
public function assets() {
wp_register_script( 'fontawesome', 'https://use.fontawesome.com/releases/v5.0.8/js/all.js' );
wp_enqueue_script( 'fontawesome' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment