base_path = ABSPATH; $this->base_url = get_home_url() . '/'; $this->default_critical_path = $this->base_path . 'wp-content/cache/awpp/critical/'; if ( ! file_exists( $this->default_critical_path ) ) { mkdir( $this->default_critical_path, 0777, true ); } } public function run() { add_action( 'awpp_settings', [ $this, 'register_settings' ] ); add_filter( 'awpp_sanitize_criticalcss', [ $this, 'minify_criticalcss' ] ); add_action( 'admin_bar_menu', [ $this, 'add_toolbar_item' ] ); if ( awpp_is_frontend() ) { add_action( 'wp_head', [ $this, 'add_critical_css' ], 1 ); } } public function register_settings() { $section = awpp_settings()->add_section( awpp_settings_page_assets(), 'ccss', __( 'Above the fold CSS', 'awpp' ) ); if ( ! awpp_get_setting( 'deliverycss' ) ) { $content = '
' . __( 'Please enable "Optimize CSS Delivery". With a normal css delivery, this option is not necessary.', 'awpp' ) . '
'; awpp_settings()->add_message( $section, 'ccssmessage', __( 'Critical CSS', 'awpp' ), $content ); } else { $path = apply_filters( 'awpp_critical_dir', $this->default_critical_path ); if ( $this->default_critical_path != $path ) { $content = ''; // translators: Custom critical directory found: code $content .= '' . sprintf( __( 'Custom critical directory found: %s', 'awpp' ), '' . $path . '' ) . '
' . __( 'Folder does not exist!', 'awpp' ) . '
'; } if ( ! is_file( $path . 'index.css' ) ) { $content .= '' . __( 'index.css does not exist!', 'awpp' ) . '
'; } awpp_settings()->add_message( $section, 'ccssmessage', __( 'Critical CSS', 'awpp' ), $content ); } else { $file = $this->default_critical_path . 'index.css'; if ( ! file_exists( $file ) ) { fopen( $file, 'w' ); } $file_url = str_replace( $this->base_path, $this->base_url, $file ); $val = file_get_contents( $file ); $args['after_field'] = "File: $file_url
"; awpp_settings()->add_textarea( $section, 'criticalcss', __( 'Critical CSS', 'awpp' ), $val, $args ); } } } public function minify_criticalcss( $css ) { $path = plugin_dir_path( awpp_get_instance()->file ) . 'Classes/Libs'; require_once $path . '/minify/autoload.php'; require_once $path . '/path-converter/autoload.php'; $minifier = new \MatthiasMullie\Minify\CSS( $css ); $minifier->minify( $this->default_critical_path . 'index.css' ); return $minifier->minify(); } /** * Toolbar */ public function add_toolbar_item( $wp_admin_bar ) { $html = ''; $html .= ''; $html .= ''; $args = [ 'id' => awpp_get_instance()->Init->admin_bar_id . '-criticalcss', 'parent' => awpp_get_instance()->Init->admin_bar_id, 'title' => __( 'Critical CSS', 'awpp' ), 'href' => '', 'meta' => [ 'class' => awpp_get_instance()->prefix . '-adminbar-criticalcss ' . ( awpp_get_setting( 'deliverycss' ) ? '' : 'disabled' ), ], ]; if ( awpp_is_frontend() && awpp_get_setting( 'deliverycss' ) ) { $args['meta']['html'] = '