wordpress 只在主页中缩小html

wqsoz72f  于 2022-11-02  发布在  WordPress
关注(0)|答案(2)|浏览(204)

我用这段代码来缩小WordPress中的HTML输出。它在主页和帖子页面上工作得很完美,但是在管理部分它会引起很多问题。

function minify_html(){
    ob_start('html_compress');
}

function html_compress($buffer){

    $search = array(
        '/\n/',         // replace end of line by a space
        '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
        '/[^\S ]+\</s',     // strip whitespaces before tags, except space
        '/(\s)+/s',     // shorten multiple whitespace sequences,
        '~<!--//(.*?)-->~s' //html comments
    );

    $replace = array(
        ' ',
        '>',
        '<',
        '\\1',
        ''
    );

    $buffer = preg_replace($search, $replace, $buffer);

    return $buffer;
}

add_action('wp_loaded','minify_html');

使用'the_post'而不是'wp_loaded'只会缩小帖子,但我希望能够100%缩小主页和帖子页面,但在管理部分没有任何内容。我如何合并这些操作来管理它?
谢谢你,谢谢你

blmhpbnm

blmhpbnm1#

不错的代码,排除管理员:

if (!(is_admin() )) {
function minify_html(){
    ob_start('html_compress');
}

function html_compress($buffer){

    $search = array(
        '/\n/',         // replace end of line by a space
        '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
        '/[^\S ]+\</s',     // strip whitespaces before tags, except space
        '/(\s)+/s',     // shorten multiple whitespace sequences,
        '~<!--//(.*?)-->~s' //html comments
    );

    $replace = array(
        ' ',
        '>',
        '<',
        '\\1',
        ''
    );

    $buffer = preg_replace($search, $replace, $buffer);

    return $buffer;
}

add_action('wp_loaded','minify_html'); }

它工作得很好WP管理员!

z9ju0rcb

z9ju0rcb2#

有一个故障排除案例,用preg_replace替换空格会导致UTF-8字符无效。(例如:à编码将失败并导致)。这是由于当前区域设置与定义的区域设置不匹配。我们可以使用/u标志作为正确过滤UTF-8字符的方法。
在某些情况下,从内联<script>标记中删除新行和多个空格将导致脚本中断。隔离<script>标记的内容将防止这种情况发生,这是通过将缓冲区拆分为一个数组来实现的,该数组由通过preg_split()打开和关闭脚本标记来分隔。

<?php

/**
 * Turn on output buffering, prettify and minimy the HTML output.
 * 
 * @see https://www.php.net/manual/en/function.ob-start.php
 * 
 * @since 1.0.0
 */
add_action( 'wp_loaded', function () {

    ob_start( function ( $buffer ) {

        /**
         * preg_replace() UTF-8 troubleshooting.
         * 
         * Replacing empty space with preg_replace causes invalid characters with UTF-8.
         * As preg_replace() depends on the current defined locale, characters not supported will be returned as � invalid.
         * The /u flag is used to make regex unicode aware.
         * 
         * @see https://stackoverflow.com/a/74101068/3645650
         */
        $replace = array(
            '/\n/smu'                   => '',      //Remove new lines.
            '/(\s)+/smu'                => '\\1',   //Replace multiple spaces with a single one.
            '/\s*<\s*/smu'              => '<',     //Remove spaces before and after opening tags.
            '/\s*>\s*/smu'              => '>',     //Remove spaces before and after closing tags.
            '/\s*\/>\s*/smu'            => '>',     //Remove spaces before and after closing tags for self closing tags.
            '/<!--(.|\s)*?-->/'         => '',      //Remove HTML comments.
            '/\s*=\s*\'([^\']*)\'/smu'  => '="$1"', //Replace single quotes with double quotes within attributes.
        );

        /**
         * preg_replace() inline <script> troubleshooting.
         * 
         * In some instances, removing new lines and multiple spaces from inline <script> tags will cause the script to break.
         * Isolating the <script> tag's content will prevent this from happening which is done by splitting the buffer into an array delimited by opening and closing script tags through preg_split().
         * 
         * @see https://stackoverflow.com/a/10423788/3645650
         */
        $buffer = preg_split( '/(<\/?script[^>]*>)/', $buffer, null, PREG_SPLIT_DELIM_CAPTURE );

        foreach ( $buffer as $key => $value ) {

            //If the $key is a <script> opening tag, $key + 1 is the script tag's content, $key + 2 is the script closing tag.
            if ( false !== stripos( $value, '<script' ) ) {

                $k = $key;

            };

            //$key + 1 is the script tag's content, which we want to ignore.
            if ( $k + 1 === $key ) {

                unset( $k );

                continue;

            };

            $buffer[ $key ] = preg_replace( array_keys( $replace ), array_values( $replace ), $value );

        };

        return implode( '', $buffer );

    } );

} );

/**
 * Get current buffer contents and delete current output buffer.
 * 
 * @see https://www.php.net/manual/en/function.ob-get-clean.php
 * 
 * @since 1.0.0
 */
add_action( 'shutdown', function () {

    ob_get_clean();

} );

相关问题