*/ final class Medivot_Chat_Widget { /** * Script handle. */ const HANDLE = 'medivot-chat-widget'; /** * Hook everything up. */ public static function register() { add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue' ) ); add_filter( 'script_loader_tag', array( __CLASS__, 'script_tag' ), 10, 2 ); } /** * Whether the widget should load on the current front-end request. * * @return bool */ public static function should_load() { $load = (bool) Medivot_Plugin::get( 'chat_enabled' ) && '' !== (string) Medivot_Plugin::get( 'widget_key' ); /** * Filters whether the Medivot chat widget loads on the current page. * Return false to hide it on specific pages. * * @param bool $load Whether the widget loads. */ return (bool) apply_filters( 'medivot_show_chat_widget', $load ); } /** * Enqueue the widget script in the footer. */ public static function enqueue() { if ( ! self::should_load() ) { return; } wp_enqueue_script( self::HANDLE, Medivot_Plugin::app_url() . '/chat-widget.js', array(), MEDIVOT_VERSION, array( 'in_footer' => true, 'strategy' => 'async', ) ); } /** * Add the widget key (and defer, as in Medivot's own snippet) to the tag. * * @param string $tag Script tag HTML. * @param string $handle Script handle. * @return string */ public static function script_tag( $tag, $handle ) { if ( self::HANDLE !== $handle ) { return $tag; } // The external tag is the only one with a src attribute; insert before it. $at = strpos( $tag, ' src=' ); if ( false === $at ) { return $tag; } $attributes = ' data-widget-key="' . esc_attr( (string) Medivot_Plugin::get( 'widget_key' ) ) . '"'; if ( false === strpos( $tag, ' async' ) ) { $attributes .= ' async'; } if ( false === strpos( $tag, ' defer' ) ) { $attributes .= ' defer'; } return substr_replace( $tag, $attributes, $at, 0 ); } }