6

禁用 WordPress 5.9 更新以及移除向前台添加的内联样式和 Svg 图像等多余代码

 2 years ago
source link: https://qq52o.me/2801.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

禁用 WordPress 5.9 更新以及移除向前台添加的内联样式和 Svg 图像等多余代码

wordpress-59.png!blog

WordPress 在 2022 年 1 月 25 日发布了 5.9 版本,取名为:Josephine

在此版本中发布了一个新的默认主题:2022, WordPress 历史上的第一个默认块主题。

这不仅仅是一个新的默认主题,同时也是使用 WordPress 主题的全新方式。

WordPress 对于前端的处理是越来越多,但对于后端 PHP 来说,支持的更少了,原以为会支持 PHP8.1 版本,但是体验后发现还是不太兼容 PHP 8.1。

最近的版本发布主要围绕着新版编辑器古腾堡 (Gutenberg) 古德堡编辑器,进行可视化、模块化。

而我还是继续使用原始的编辑器,暂时用不到区块编辑器,为什么呢?

因为我用 Markdown 写内容,并且自己写了插件进行解析操作,WordPress 目前只是相当于提供了功能、插件、主题的一些功能。

这些更新对我来说没有任何意义,所以我放弃了更新 WordPress 内核。

在主题的 functions.php 中添加:

// 禁用核心更新
add_filter('pre_site_transient_update_core', '__return_null');
remove_action('admin_init', '_maybe_update_core');

就可以移除更新检测和后台中 WordPress 5.9现已可用!请立即更新。的提示

移除向前台页面添加的内联样式 Css 和 Svg 图像等多余代码

如果你升级了 WordPress 5.9 ,你就会发现:

从 WordPress 5.9 开始,WordPress 会向前端页面的头部插入了 global-styles 内联样式,并向底部插入了很多的 svg 图像(主要是 duotone block,查看页面源代搜索 duotone 就能看到了)。

对于国内主题而言,主题本身有自己的特定 CSS 样式,根本用不到 WordPress 这个新加的样式和图像,让页面平白多出了许多冗余代码...

那么如何移除掉这些东西呢?

移除头部里的 Global-Styles 内联样式

在主题的 functions.php 中添加:

/**
 * WordPress 5.9 移除头部里的 global-styles 内联 css 样式
 * https://www.ilxtx.com/disable-gutenberg-style-and-duotone-svg-images.html
 */
function remove_global_styles(){
    wp_dequeue_style( 'global-styles' );
}
add_action( 'wp_enqueue_scripts', 'remove_global_styles' );

移除底部里的 Duotone Svg 图像

在首个版本中通过 WordPress 源代码来看,并没有预留直接禁止 duotone svg 图像的钩子方法,使用 remove_filter( 'render_block', 'wp_render_duotone_support', 10); 的方法,并不能移除。

而需要使用在 WordPress 5.9 中添加的 theme.json 这个配置文件才可以。

在所使用的主题的根目录中新建一个 theme.json 文件,写入以下代码:

{
    "version": 1,
    "settings": {
        "color": {
            "duotone": null
                }
        }
}

一键移除上面的内联样式和 SVG 图像(推荐)

在主题的 functions.php 中添加:

/**
 * 移除 WordPress 5.9 向前台页面添加的内联样式 css 和 svg 图像等多余代码
 * https://www.ilxtx.com/disable-gutenberg-style-and-duotone-svg-images.html
 */
function remove_global_styles(){
    remove_action('wp_enqueue_scripts', 'wp_enqueue_global_styles');
    remove_action('wp_footer', 'wp_enqueue_global_styles', 1);
}
add_action('after_setup_theme', 'remove_global_styles', 10, 0);

移除所有区块样式

在主题的 functions.php 中添加:

function remove_wp_block_library_css(){
    wp_dequeue_style( 'wp-block-library' );
    wp_dequeue_style( 'wp-block-library-theme' );
    wp_dequeue_style( 'wc-block-style' ); // 移除WOO插件区块样式
    wp_dequeue_style( 'global-styles' ); // 移除 THEME.JSON
}
add_action( 'wp_enqueue_scripts', 'remove_wp_block_library_css', 100 );
沈唁志 任何个人或团体,未经允许禁止转载本文:《禁用 WordPress 5.9 更新以及移除向前台添加的内联样式和 Svg 图像等多余代码》,谢谢合作!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK